Skip to content

Instantly share code, notes, and snippets.

@aspyct
Created March 3, 2017 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspyct/53d7f3c3a7751e78319916233e34b41e to your computer and use it in GitHub Desktop.
Save aspyct/53d7f3c3a7751e78319916233e34b41e to your computer and use it in GitHub Desktop.
Reusable Xamarin.Android RecycledViewPool
class RecycledViewPool
{
public delegate ViewHolder Factory(ViewGroup parent, int viewType);
// A stack has a O(1) add/remove, so better than a list
Dictionary<int, Stack<ViewHolder>> pool;
Factory factory;
public RecycledViewPool(Factory factory)
{
this.pool = new Dictionary<int, Stack<ViewHolder>>();
this.factory = factory;
}
public ViewHolder GetRecycledView(ViewGroup parent, int viewType)
{
Stack<ViewHolder> recycledViews = GetOrCreatePool(viewType);
if (recycledViews.Count > 0)
{
return recycledViews.Pop();
}
else
{
return factory(parent, viewType);
}
}
public void Recycle(ViewHolder holder)
{
var recycledViews = GetOrCreatePool(holder.ViewType);
recycledViews.Push(holder);
}
Stack<ViewHolder> GetOrCreatePool(int viewType)
{
Stack<ViewHolder> recycledViewList;
if (!pool.TryGetValue(viewType, out recycledViewList))
{
recycledViewList = new Stack<ViewHolder>();
pool.Add(viewType, recycledViewList);
}
return recycledViewList;
}
}
abstract class ViewHolder
{
public int ViewType { get; private set; }
public View ItemView { get; private set; }
public ViewHolder(View itemView, int viewType)
{
ItemView = itemView;
ViewType = viewType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment