Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 539
vovahost Avatar asked May 19 '15 18:05

vovahost


People also ask

Is there an addHeaderView equivalent for RecyclerView?

addHeaderView() but you can achieve this by adding a type to your adapter for header. everything seems to be OK and it should work, but however make the recycler view MATCH_PARENT see if anything changes. also if its possible make the recycler view the root of that layout (its good for performance).

What is viewType in onCreateViewHolder?

This viewType variable is internal to the Adapter class. It's used in the onCreateViewHolder() and onBindViewHolder to inflate and populate the mapped layouts. Before we jump into the implementation of the Adapter class, let's look at the types of layouts that are defined for each view type.

What is RecyclerView setHasFixedSize?

setHasFixedSize(true) means the RecyclerView has children (items) that has fixed width and height.

What is RecyclerView LayoutManager?

A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.


2 Answers

try this:

  1. When init :
recyclerView.setItemViewCacheSize(0);
  1. When refresh data:
recyclerView.removeAllViews();

recyclerView.getRecycledViewPool().clear();
like image 199
Seabiscuit Avatar answered Oct 05 '22 17:10

Seabiscuit


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()

like image 38
Alexandre G Avatar answered Oct 05 '22 17:10

Alexandre G