Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding Views in a RecyclerView only to current item

I'm dynamically adding Views to my items in a RecyclerView. These added Views should only be related to the item which they're added to, but I'm having a problem when I scroll. It seems the View is recycled and a new item is loaded, but those previously added views are still there, only now on the wrong item.

I'm assuming that it's just because the ViewHolder is being reused, so the added items show up again with a new item, when loaded.

How would one go about solving this?

like image 584
Orbit Avatar asked Dec 31 '15 22:12

Orbit


3 Answers

This was an old question of mine. A bounty was placed on it, hence the surge of popularity and the multiple new and irrelevant answers.

As stated in both my comment to this answer and @CQM's comment below my original question, the answer is to override the onViewRecycled() method and perform any needed operations there. This method is called when a view is recycled, and any cleanup operations can be done here.

Documentation on this method can be found here.

In my case, it was a matter of deleting the invisible TextView's attached to the view. The text itself had been deleted, but the view remained. If many invisible TextView's accumulate on the view and aren't properly recycled when scrolling, the scroll will begin to lag.

like image 196
Orbit Avatar answered Oct 17 '22 06:10

Orbit


You need to track what views have been added based on the backing data. I would probably add any necessary extra views in onBindViewHolder(), and remove any that might be present in onViewRecycled(). Then when you want to make one appear dynamically, change whatever variable you have tracking whether it should be visible, and call notifyItemChanged().

like image 25
RussHWolf Avatar answered Oct 17 '22 07:10

RussHWolf


Based on this:

but those previously added Views are still there, but now on the wrong item.

Basically, as per the RecyclerView documentation, You have to reset the views everytime inside the onBindViewHolder() method,

so let say, you have a method that sets a view param if its your profile, so the code for the same goes as follows,

if (list.get(position).getId()==PreferenceManager.getUserID())
{
  // do some view change here
setViewParam(true);
}else
{
  // reset the view change here
setViewParam(false);
}

So what you're doing here is giving recycled ViewHolder a chance to reset. Do comment if you need help!

like image 24
MadScientist Avatar answered Oct 17 '22 05:10

MadScientist