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.
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.
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.
The Best Answer ispublic void clearData() { myList. clear(); // clear list mAdapter. notifyDataSetChanged(); // let your adapter know about the changes and reload view. }
Use
recyclerView.getRecycledViewPool().clear();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With