RecyclerView Multiple View Type

Nandish swarup
2 min readMar 21, 2021

RecyclerView is a very flexible and powerful widget and you might have used only one layout to display the list but you can use more than one layout in the same ViewGroup.

In this article we will take the example of two layouts in the same recyclerView, One would be the smaller cardView with two textViews and other would be the bigger layout with 3 textViews and width matches the parent as can be seen below

Step 1

RecyclerView is created on the basis of data in ArrayList. Every item in a RecylerView corresponds to an item in an ArrayList on a particular position.

So first we need to define an ArrayList of custom Bean “MultiViewBean” where the type variable will reflect different kinds of layouts.

Step 2

In your adapter, you need to override the getItemViewType() method. This method returns the int value which we will be used in other methods in adapter. In this example, if ArrayList at index 0 has type 1 then we will return VIEW_TYPE_1 else VIEW_TYPE_2 and so on.

Step 3:

Next step we will have to inflate two layouts since we are using two layouts in the recyclerView as can be seen below. On the basis of type we will inflate either of the one views at a particular position of ArrayList

Step 4:

Define viewHolder of the layouts where you can define and access the elements of the respective layouts

Step 5:

Make the following changes in the BindViewHolder() method.

RESULT:

Adapter class :

That’s it for now!!
Thanks for reading and don’t forget to share with your fellow developers :)
This post was originally posted on
CodeTheraphy.com.

For more articles follow me on Medium and CodeTheraphy.com you can also connect me on LinkedIn

--

--