![]() |
VOOZH | about |
Recycler View is a ViewGroup added to Android Studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user.
For example: if a user scrolled down to a position where the items 4 and 5 are visible; items 1, 2 and 3 would be cleared from the memory to reduce memory consumption.
In this article, we will learn how to create a Recycler View which can be scrolled in a horizontal direction. Here are the detailed steps:
Step 1: Add the dependency of Recycler View widget in your project
In modern android studio projects, Recycler View is already present, so there is no need to add a dependency for RecyclerView explicitly. However, if you are unable to use Recycler View, you can add the following dependency in your app > build.gradle.kts (module: app) file
Latest dependency for Recycler View is:
implementation("androidx.recyclerview:recyclerview:1.3.2")Also add the dependency for Card View. Latest dependency for Card View is:
implementation("androidx.cardview:cardview:1.0.0")Step 2: Setting up the activity_main.xml layout file The activity_main.xml layout file consists of:
Here is complete code for activity_main.xml:
Step 3: Setting up the item.xml layout file for Recycler view
Make a new layout file 'item.xml' in your app > res > layout folder. The item.xml layout file consists of the layout for an item of Recycler View. Item Layout contains a Card View with Text view in it with some text. Here is complete code for item.xml:
The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView.Create a new java class called 'adapter.java' in your app > java > com.package.package folder.
The basic methods for a successful implementation are:
The adapter is used to set data to Recycler View from Data source. Here is complete code for adapter.java:
Javapackage com.ishaanbhela.recyclerviewexample;
Step 5. Setting up the code for MainActivity.java file for Recycler view
The MainActivity contains RecyclerView. Set Layout Manager on Recycler view using LinearLayoutManager class. Here is complete code for MainActivity.java: