Android – RecyclerView: How to clear the recycled views from RecyclerView.RecycledViewPool

androidandroid-recyclerview

Here is the situation: RecyclerView item views have a complex layout.

At some point I modify the layout for RecyclerView items this way:

Ex. Index of modified View inside itemView = 3;

for (int i=0; i < mRecyclerView.getChildCount(); i++) {

    ViewGroup itemView = ((ViewGroup) mRecyclerView.getChildAt(i));

    itemView.getChildAt(3).getLayoutParams().width = newWidth;
    itemView.getChildAt(3).requestLayout();
} 

It all works as expected but when I scroll the RecyclerView there are 2-3 recycled item views that will appear with the old width. Now I'm trying to find how to remove these views from RecycledViewPool or even a better solution: to modify their width too but I can't find a way to get those views.

I tried mRecyclerView.getRecycledViewPool().clear() but the old views keeped reappearing.

Best Solution

To prevent RecyclerView caching the detached but not recycled views use:

mRecyclerView.setItemViewCacheSize(0)

Another slightly more radical way is to call notifyDataSetChanged() or notifyItemChanged() for the items you expect to be cached - this will force them to get recycled and you will be able to update them in onBindViewHolder()