Skip to content

Instantly share code, notes, and snippets.

@alexoro
Created July 29, 2019 10:22
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexoro/81b75a7edae77bb7db7d6132c0e76848 to your computer and use it in GitHub Desktop.
Save alexoro/81b75a7edae77bb7db7d6132c0e76848 to your computer and use it in GitHub Desktop.
RecycledViewPool with unlimited number of ViewHolders
package com.vk.im.ui.utils.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
/**
* RecycledViewPool with unlimited number of ViewHolders
* {@author uas.sorokin@gmail.com}
*/
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