У меня есть список отраслей, установленных в адаптере. Каждый раз, когда я нажимаю/выбираю отрасль, меняются имя и цвет фона. Но когда я пытаюсь ниже код, предыдущая выбранная промышленность не изменится его цвет по умолчаниюУдалить последнее выбранное положение OnClick в Recycler View adapter
@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 –