Created
March 3, 2017 09:34
-
-
Save aspyct/53d7f3c3a7751e78319916233e34b41e to your computer and use it in GitHub Desktop.
Reusable Xamarin.Android RecycledViewPool
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
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; | |
} | |
} |
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
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