Working with RecyclerView in Kotlin
RecyclerViews in Android is one of the most interesting concepts to become a master in Android. There are a lot of different examples and implementations across the internet. Learn first, what a RecyclerView is before implementing it.
What is a RecyclerView?
A RecyclerView is a flexible view for providing a limited window into a large data set. It is essentially a ViewGroup of containers called ViewHolders which populate a particular item. RecyclerView is an extensive Android class to provide a flexible UI. A great benefit of using RecyclerViews is that you’re able to efficiently reuse views instead of managing items that aren’t even visible to a user.
Why we use RecyclerView?
In the past, Android was using ListView or GridView classes for displaying lists. The RecyclerView can be described as a combination of a ListView and a GridView. However, in a RecyclerView, there are features that separate your code into maintainable components while also enforcing memory-efficient design patterns.
How is it better than ListViews and GridViews?
ListViews and GridViews are comparatively slower than RecyclerViews.
Layouts in RecyclerView
The RecyclerView changed everything which was used in the ListView and GridView. RecyclerView still uses an Adapter to act as a data source. However, you have to create ViewHolders to keep references in memory.
To provide a new view, RecyclerView either creates a new ViewHolder object to inflate the layout and hold those references, or it recycles one from the existing stack.
This is it why it’s called a RecyclerView!
The Views in RecyclerView comes with default animations that you don’t have to create or add yourself.
RecyclerView requires a ViewHolder, the RecyclerView knows which animation to apply to which item and adds them as required. You can also create your own animations and apply them as needed.
The most important and interesting component of a RecyclerView is its LayoutManager. This object positions the RecyclerView’s items and tells them when to recycle items that have transitioned off-screen. The ListView used to do this work by itself.
The RecyclerView has broken out of this functionality to allow for different kinds of layouts: Vertical, Horizontal, Grid, Staggered, or your own!
There are three types of Layout Managers by default:
- LinearLayoutManager: Positions items to look like a standard ListView.
- GridLayoutManager: Positions items in a grid format similar to a GridView.
- StaggeredGridLayoutManager: Positions terms in a staggered grid format.
RecyclerView implementations requires:
- A list of data objects to work with.
- An XML file of the view item.
- An adapter to bind that data to the views.
- A ViewHolder to populate the UI view from the XML item file.
Now we are familiar with what RecyclerView is and its basics, let’s get into the implementation.
Get started with RecyclerView
Create a New Project
Create a new Android Studio project using Kotlin.
Select option as Start a new Android Studio project.
Select Empty Activity and click on Next.
Add the name of the project as RecyclerViewApp and update the package name as you want and select the project location where you want to save the project.
Create a project using Kotlin.
Once the project is loaded go inside the activity_main.xml and remove the Hello World TextView.
Add the dependency in the build.gradle (:app) :
Add the RecyclerView
Add the RecyclerView in an activity layout activity_main.xml layout file and add the following code.
Assign the id to the RecyclerView as “android:id=”@+id/recycler_view_items“.
Create a Custom Layout file
Add the custom layout file for RecyclerView as item_custom_row.xml in the resource layout.
Setup the data resource
Add the below function in the MainActivity.kt.
We have created a list of 15 elements which will be displayed using RecyclerView.
Create an Item Adapter Class
Create an Item Adapter class named ItemAdapter.kt.
Create the view holder for view items, connect the data source of the RecyclerView and handle the view logic by creating a RecyclerView Adapter.
We have used the custom layout file to bind the views to the RecyclerView. In the onCreateViewHolder function we have inflated it.
In the onBindViewHolder function we have set the text to the TextView from the data list. Also, we have add the different background colors to the CardView based on the odd and even positions.
Add the below colors in the colors.xml file.
Now, as we have everything that is required.
Attach the adapter to the RecyclerView.
After, attaching the RecyclerView to the adapter class the MainActivity.kt will look like this:
The LayoutManager used here is LinearLayoutManager for the RecyclerView.
Adapter class is initialized and data list is passed to it.
Finally, the adapter class is attached to the RecyclerView.
Run the app and check the output.
Output using the LinearLayoutManager
RecyclerView using LinearLayoutManager with Horizontal Scroll
As we can see in the above output the items are displayed in the vertical format and can be scrolled vertically.
Now add some more parameters using the LinearLayoutManager we can also display the items in the horizontal format.
By default the scrolling direction it vertical.
For the horizontal we need to pass the direction as LinearLayoutManager.HORIZONTAL and reverse layout as true or false as per requirement.
Now you will be able to scroll the items in the horizontal format.
Output using the LinearLayoutManager in Horizontal Scroll
RecyclerView using GridLayoutManager
Now display the items views using the GridLayoutManager instead of LinearLayoutManager in the RecyclerView.
Replace the layout manager in the MainActivity.kt onCreate function.
Replace the below line of code.
Replace it with GridLayoutManager.
In the GridLayoutManager you need to pass the span count as in our case it is 2 which will impact the grid column count.
Output using the GridLayoutManager
RecyclerView with Multiple View Types
You might have noticed and seen that while using a RecyclerView, we define a view and the list items are displayed according to that view only. But what if you want to add different view types in the RecyclerView, you can add Multiple Views in the same RecyclerView.
We can add multiple views in a single RecyclerView. For example, the home page on Facebook and Instagram is an example of Multiple Views. You can add an image, video, text or a combination of all of them in the same RecyclerView.
We’ll use the same project that we have done above and make the changes for another view type.
We’ll use the LinearLayoutManager as the layout manager in the RecyclerView.
For LinearLayoutManager replace the layout manager line in MainActivity.kt as below.
recycler_view_items.layoutManager = LinearLayoutManager(this)
Create a Another Custom Layout file
Add the custom layout file for RecyclerView as item_another_custom_row.xml in the resource layout.
Create a Data Model Class
The data model class is used to create a custom data type list.
Create the data model class name as DataModel.kt.
Update an Item Adapter Class
In the Item adapter class we need to make the following changes as below:
- Update the list data type from string to data model class.
- Update the implementation parameter as RecyclerView.ViewHolder instead of ItemAdapter.ViewHolder.
- Declare the constants for View Types in companion object.
- Override the function as getItemViewType.
- Add another viewholder inner class.
- Update the onCreateViewHolder and onBindViewHolder functions as per view types.
- The ItemAdapter.kt will look like below.
Update Data Resource List
Update the data resource list using data model class as DataModel.kt.
Update the getItemsList function in MainActivity.kt as below.
Output of Multiple View Types
That’s the basics of RecyclerViews. That’s all you need to know to create RecyclerViews in your app as per your requirements. You can change the kind of layout you want to work in the LayoutManager with other managers such as GridLayoutManager. You can substitute your view as per your app design. The implementation is relatively flexible. Now, you are able to create better views using RecyclerView with Vertical and Horizontal scrolling and as well with GridView. You can also create a view like in the Facebook App which uses Multiple Views in the same RecyclerView. Happy coding.