RecyclerView is the recommended way to represents a collection of items in Android applications, the good and old ListView is now deprecated since RecyclerView offers a lot of improvements like flexible layout, item recyclying and enforces the ViewHolder pattern.
If you’re new to RecyclerView in Xamarin Android I recommend this article from Xamarin site, since it is also the origin project I’ve used on this post and this is not a RecyclerView tutorial.
This post originates since every time I need to use a RecyclerView, even for simple demos like this blog post, I end up rewriting the same boilerplate code, so I decided to create a simple generic adapter that simplifies things for me.
Source code and demo is available on GitHub here, so get it and have a look if you want to know more about the internals, I’ll just show you how to use it updaing the original Xamarin demo.
Just create a class that inherits from abstract SmartRecyclerAdapter<T> class
as you see, you just have to implement two methods OnLookupViewItems and OnUpdateView: OnLookupViewItems is used to extract the view items from inflated layout and save them into provided generic viewholder
OnUpdateView is used to update the same view items with the fresh values coming from provided Item.
Let’s see now in action, exploring the code in MainActivity:
Very simple: I created an instance of the PhotoRecyclerAdapter passing to its constructor: the RecyclerView, an ObservableCollection<T> as item source and the optional id of the layout to inflate to create the items views (more on this later)
Since we’re using an ObservableCollection<T> the list is smart enough to automatically invoke the several NotifyXYZ methods when you add/remove/move items from the collection as when the “Clear+Add” button of the demo is clicked.
What if you need to use different layouts depending on items properties? just override base class GetViewIdForType method and return an int that will be passed to the othere method you’ll have to override named OnGetViewId inside this method, depending on passed viewTypeId you’ll return the item id to inflate for such element.
The adapter automatically raises an ItemSelected event when an item is clicked, passing null as RecyclerView parameter on PhotoRecyclerAdapter constructor, disables this behavior and you can implement your own item selection strategy.
It’s just a starting point, hope you’ll like it.