Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView: how to clear cached/recycled views?

I use a RecyclerView to display a list of items with a list layout. I switch from a list layout to a grid layout, showing just a subset of all the data when in grid layout. This switch uses a different layout XML than when list layout is presented.

All this works well, except that when I scroll, recycled (cached?) list layout views populate the grid, mixed in with proper grid layout view items. In other words, instead of using my layout_grid.xml for each item's layout in the RecyclerView, I get items using the layout_list.xml layout, but in a grid format.

This tells me the LayoutManager is working correctly, switching from a list to grid layout. But not all item view items are recreated using the grid xml layout, but rather recycled list layout views are used.

I tried RecyclerView.removeAllViews(), RecyclerView.removeAllViewInLayout(), RecyclerView.swapAdapter() (to force adapter reload), all to no avail.

Update:

If I scroll two positions down in the list, and then switch from list to grid, the first two positions do not go through onCreateViewHolder(), but straight to onBindViewHolder() and are therefore not forced to use the grid layout xml. Instead those first two position items are recycled (I think) and displayed in their list layout format.

like image 710
mraviator Avatar asked Jan 14 '15 20:01

mraviator


People also ask

How do I empty the RecyclerView cache?

Only way to do is by using notifyDataSetChanged for all items. Recyclerview will remove views from cache and add those to recyler views pool. So now, when LM asks for view, either recycled view(according to itemType) or newly created view will be returned, and adapter will bind data to these views.

How do you refresh a recycler view?

The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views.

How do I clear my RecyclerView adapter?

The Best Answer ispublic void clearData() { myList. clear(); // clear list mAdapter. notifyDataSetChanged(); // let your adapter know about the changes and reload view. }


2 Answers

Use

recyclerView.getRecycledViewPool().clear(); 
like image 127
Oleg Kovalyk Avatar answered Oct 08 '22 23:10

Oleg Kovalyk


I had the same problem. The solution suggested by Mann works well. An other option would be to set the RecycledViewPool of the RecyclerView to a new instance. That works for me as well.

recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool()); 

But I think overriding the getItemViewType() is the cleaner solution.

like image 41
goflo Avatar answered Oct 09 '22 00:10

goflo