I have a RecyclerView and respective adapter in which I created OnItemClickListener interface.
I try to pass the (onclicked) view itself to the implementation in the Activity and it gets multiple items. In fact, the change I want to make on an view item affects more than one item in the recycler view list. I want to change the background of an item in the list, but another item's background changes, too.
Here is the adapter:
public class TranslationAdapter extends RecyclerView.Adapter<TranslationAdapter.TranslationHolder> {
private List<String> translations = new ArrayList<>();
private OnItemClickListener listener;
@NonNull
@Override
public TranslationHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.translation_item, viewGroup, false);
return new TranslationHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull TranslationHolder translationHolder, int i) {
...
}
public void setTranslations(List<String> _translations){
this.translations = _translations;
notifyDataSetChanged();
}
class TranslationHolder extends RecyclerView.ViewHolder{
private TextView tvTranslation;
public TranslationHolder(@NonNull final View itemView) {
super(itemView);
tvTranslation = itemView.findViewById(R.id.text_view_translation);
itemView.setOnClickListener(v -> {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION){
listener.onItemClick(v, translations.get(position));
}
});
}
}
public interface OnItemClickListener{
void onItemClick(View view, String string);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
}
and here is the implementation in the Activity:
public class TranslationActivity extends AppCompatActivity {
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translation);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
super.onStart();
adapter.setOnItemClickListener((v, translation) -> {
if (arrResultOfTranslation.contains(translation)){
arrResultOfTranslation.remove(translation);
v.setBackgroundColor(Color.BLUE);
}
else {
v.setBackgroundColor(Color.YELLOW);
arrResultOfTranslation.add(translation);
}
});
}
}
As result, although I get only one string item (translation), multiple items' background color change. When I debug I see only one View instance (variable v).