Sir, Here is a Handcrafted RecyclerView for You
On the one hand, ListView had a pretty straightforward way to handle click events, all you had to do was to implement the OnItemClickListener() method. That was it.
On the other hand, RecyclerView is much more flexible but demanding. You have to implement the click listeners by yourself. Don’t panic, this is neither a bad nor a hard thing to do. The idea is to allow you to customize this behavior according to your needs, in case you want to use a grid instead of a list, for example.
Currently there are several ways of handling click events:
- Implement the listeners in the Activity or Fragment
- Implement the listeners in your RecyclerView Adapter
- Implement the listeners in your item’s ViewHolder class
Here is an example of how to implement this according to the most upvoted answer in Stackoverflow regarding click events on RecyclerView.
RowViewHolder.java:
RecylerViewAdapter.java:
Using different layouts
One of the great things about RecyclerView is that it can handle different layouts for its items. Doing so will be responsibility of the Adapter.
Below, you will see the code used to create a loader item’s layout (based on the best answer in Stackoverflow).
RecylerViewAdapter.java:
Related post: Every Rose has its Thorns
Additional notes
- Setting recyclerView.setHasFixedSize(true); optimizes the Recycler if changes in the adapter content cannot change the size of RecyclerView itself. Set this true if you don’t need to dynamically change your Recycler’s size.
- RecyclerView does not come with default dividers. With ListViews you can set a default divider for the rows by using the XML attributes android:divider and android:dividerHeight. For RecyclerViews you can place the dividers in your item’s layout, code a custom implementation of RecyclerView.ItemDecoration or decide not to use dividers at all.
By now you probably have an idea of how the RecyclerView works and how to get the most from it. Despite of this, there are some things left to say about this widget that may raise some red flags.
Don’t forget to read the final part of the post to find out!
Posted by Juan Ignacio Molina (juan.molina@wolox.com.ar)