Android RecyclerView Tutorial

The new support library in Android L introduced two new UI widgets: RecyclerView and CardView. The RecyclerView is a more advanced and more flexible version of the ListView. This new component is a big step because the ListView is one of the most used UI widgets. The CardView widget, on the other hand, is a new component that does not “upgrade” an existing component.

What is RecyclerView ?

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. RecyclerView can be used for larger datasets to be rendered on the UI like a list. RecyclerView provides maximum flexibility to design different kind of views .

RecyclerView Features

– ViewHolder to store data that makes binding view contents easier .
– ItemDecorator to set special drawing and layout offset .
– SmoothScroller for smooth scrolling .
– LayoutManager (LinearLayoutManager,GridLayoutManager,StaggeredGridLayoutManager)
– By Default Animations while adding or removing an item .

Let’s Get it Working

In this tutorial we are going to learn how to render a simple RecyclerView with a custom layout. We’ll also learn writing a adapter class, adding list divider and row click listener. The recycler view we are going to design contains list of books displaying the title and author .

Step 1 ) Update build.gradle file

Before you can use RecyclerView in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project .

Step 2 ) Modify activity_main.xml

Step 3 ) Write Book model class

Create a class named and declare title and author. Also add the getter/setter methods to each variable.

Step 4 ) List Row layout

Create an layout xml named book_list_row.xml with the below code. This layout file renders a single row in recycler view by displaying book title and author .

Step 5 ) Writing the Adapter Class

Create a class named and add the below code. Here onCreateViewHolder() method inflates book_list_row.xml. In onBindViewHolder() method the appropriate book data (title and author) set to each row.

Step 6 ) Binding Adapter and RecyclerView

Open and update the below changes. Here initBookData() method sets the sample data to recycler view.

Run your app , you can see the books in list .


Enjoy Coding and Share Knowledge

Show Buttons
Hide Buttons