Posted on

Android RecyclerView


android recyclerview
Designed by Freepik

Let’s look at how to use Android RecyclerView and why should you use it over ListView

In my previous post, we looked at why RecyclerView is better than ListView. Although it’s more code than with ListView, it’s very simple and readable

Model

First, let’s create a model to display

List Item Layout

With ListView you usually start with using default layout that has a TextView. You can do the same with RecyclerView, but it doesn’t make sense in most cases. Let’s create our own list_item.xml

Holder

There should be a class that holds a reference to inflated list item layout and has references to views. Those instances are reused by RecyclerView.Adapter

Adapter

Next, there should be a class that handles setting data to layouts for the particular position of the list. It also does optimizations with recycling created list items when scrolling

Main Layout

Now you need to display RecyclerView in your activity layout

Main Activity

Finally, setup RecyclerView in activity and populate it with some items

 

Don’t forget to always setLayoutManager. It’s a method I always forgot to call in the beginning and then waste bunch of time trying to figure out why RecyclerView doesn’t display anything

Also, if you want to learn how to use RecyclerView with Data Binding – check this post

Hope it helps, don’t forget to subscribe, follow me on Twitter, Facebook, G+ to get notified about the latest posts!