我有一個在適配器中設置的行業列表。每次點擊/選擇一個行業,名稱和背景顏色都會發生變化。但是,當我嘗試下面的代碼,以前選擇的行業不改變它的默認顏色清除最後選擇的位置OnClick in Recycler查看適配器
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.setIsRecyclable(false);
holder.txtIndustry.setText(industries.get(position).getIndustryName().trim());
holder.txtIndustry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedPosition = holder.getAdapterPosition();
// Highlight the background and change the text color.
if (selectedPosition == position) {
holder.itemView.setBackgroundColor(context.getResources().getColor(R.color.text_color_blue));
holder.txtIndustry.setTextColor(Color.WHITE);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
holder.txtIndustry.setTextColor(context.getResources().getColor(R.color.text_color_blue));
}
notifyItemChanged(selectedPosition);
callback.selectedIndustryPosition(position);
}
});
}
爲上述問題的解決方案是:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
industry = industries.get(position);
holder.setIsRecyclable(false);
holder.txtIndustry.setText(industry.getIndustryName().trim());
if (holder.getAdapterPosition() == selectedPosition) {
// Highlight the background and change the text color.
holder.itemView.setBackgroundColor(context.getResources().getColor(R.color.text_color_blue));
holder.txtIndustry.setTextColor(Color.WHITE);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
holder.txtIndustry.setTextColor(context.getResources().getColor(R.color.text_color_blue));
}
holder.txtIndustry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedPosition = holder.getAdapterPosition();
callback.selectedIndustryPosition(selectedPosition);
notifyDataSetChanged();
}
});
}
您的代碼不起作用。它選擇每個視圖 –
您是否已初始化selectedPosition = -1以及適配器的其他變量? – Anjali
是的,int selectedPosition = -1 –