Select items in RecyclerView

android, android-recyclerview

Solution

Make global variable to store position and handle click listener in `ViewHolder`. `Onclick` of item, change the global position value like

textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        globalPosition=getAdapterPosition();
        notifyDataSetChanged();
    }
});

then in `onBindViewHolder`

if(postion==globalPosition)
{
    //change color like
    textview.setTextColor(Color.RED);
}
else
{
    //revert back to regular color 
    textview.setTextColor(Color.WHITE);
}

with this code, the item you clicked get red colored and all other wiil be in white.

Problem

Similar question have been asked, but i can't get any of them work. What i want is to select item in RecyclerView, change the background of that item view, and store the position of item selected. The main problem is that you have onCreateViewHolder (in adapter), onBindViewHolder (in adapter) and ViewHolder constructor and everybody is working with different methods. Now, i don't even know where to put onClickListener (in previous projects i've put it in ViewHolder), because people are suggesting the other two methods too. My idea was to store each ViewHolder (or View) in list, so i can have reference to each row, and change the background from there. But that didn't work for me, because when i try to add to list of View(or ViewHolders), from any of three places (onCreateVH, onBindVH, VH class), my app crashes for some reason (null pointer ex). Any suggestions? Where and how to implement it?

Original source