How to make Expandable RecyclerView using Kotlin

How to make Expandable RecyclerView using Kotlin

Today, I’m going to show you how to make an expandable RecyclerView with smooth animation without using 3rd party libraries.

We’re going to use a custom class named ExpandableLayout, created by SilenceDut.

It’s a custom LinearLayout class that handles the expand-collapse animations using the ValueAnimator.

Making Expandable RecyclerView

First, let’s add the custom class ExpandableLayout in the project.

Go to your package name on the left side and press right click > New > Kotlin File/Class

Give the name ExpandableLayout, choose Class and press OK.

Inside this file, paste the following code:

Now, go to res folder and right-click on the values folder > New > Values resource file.

In the new window, give the name attr and press OK

…and paste the following code:

Go to your Activity’s XML file and paste the following code to add a RecyclerView

And for the cell of the RecyclerView:

With ExpandableLayout you need to have 2 layouts inside. One for the cell, in this example is the Question, and one for the view that expand-collapse below the cell when the user clicks on it (Answer).

Set up your RecyclerView in your Activity (MainActivity.kt).

And for the RecyclerViewAdapter:

Done!

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

9
Leave a Reply

avatar
3 Comment threads
6 Thread replies
5 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
John CodeospareshMobiAndyAyush JainArtenes Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Artenes
Guest
Artenes

Nice implementation. I’ve also made one some time ago, but it is very simples compared to yours: https://github.com/Artenes/recycler-view-expand-collapse.

Will study your code later to learn more on how to properly implement this expansion animation.

Ayush Jain
Guest
Ayush Jain

Nice read but just curious that why to do so much hard work because we can use one boolean variable in each item of list to make it’s expanded part to visible / invisible. And recyclerview gives pretty nice animation also for that i.e. slide up/down.

paresh
Guest
paresh

what is Arraylist
i am geetting error unresolved referrence
which library to import for this

Follow me