Created
July 29, 2019 10:22
-
-
Save alexoro/81b75a7edae77bb7db7d6132c0e76848 to your computer and use it in GitHub Desktop.
RecycledViewPool with unlimited number of ViewHolders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vk.im.ui.utils.recyclerview; | |
import android.support.v7.widget.RecyclerView; | |
import android.util.SparseIntArray; | |
/** | |
* RecycledViewPool with unlimited number of ViewHolders | |
* {@author [email protected]} | |
*/ | |
public class NoLimitRecycledViewPool extends RecyclerView.RecycledViewPool { | |
private static final int DEFAULT_MAX_SIZE = 5; | |
private final SparseIntArray scrapCount = new SparseIntArray(); | |
private final SparseIntArray maxScrap = new SparseIntArray(); | |
public NoLimitRecycledViewPool() { | |
} | |
@Override | |
public void setMaxRecycledViews(int viewType, int max) { | |
maxScrap.put(viewType, max); | |
super.setMaxRecycledViews(viewType, max); | |
} | |
@Override | |
public RecyclerView.ViewHolder getRecycledView(int viewType) { | |
final RecyclerView.ViewHolder r = super.getRecycledView(viewType); | |
if (r != null) { | |
final int count = scrapCount.get(viewType, -1); | |
if (count <= 0) { | |
throw new IllegalStateException("Not expected here. The #put call must be before"); | |
} else { | |
scrapCount.put(viewType, count - 1); | |
} | |
} | |
return r; | |
} | |
@Override | |
public void putRecycledView(RecyclerView.ViewHolder scrap) { | |
final int viewType = scrap.getItemViewType(); | |
final int count = scrapCount.get(viewType, 0); | |
scrapCount.put(viewType, count + 1); | |
int max = maxScrap.get(viewType, -1); | |
if (max == -1) { | |
max = DEFAULT_MAX_SIZE; | |
setMaxRecycledViews(viewType, max); | |
} | |
if (count + 1 > max) { | |
setMaxRecycledViews(viewType, count + 1); | |
} | |
super.putRecycledView(scrap); | |
} | |
@Override | |
public void clear() { | |
scrapCount.clear(); | |
maxScrap.clear(); | |
super.clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment