Android Expandable List View Tutorial


Expandable List View is a view that shows items in a vertically scrolling two-level list. It is different to list view as it allows two levels: groups that can individually be expanded to show its children. Each group can be expanded or collapsed individually to show or hide its children items. Basic usage of expandable list view is to group data by categories.

Let’s Get it Working

In this tutorial we are going to learn how to use Expandable List View. To really understand the usage of Expandable List View we will create an app . The App contains simple list view having groups and its childrens. This app shows how Expandable List View expands, collapses and click actions. I assume that you have created a new android project. Source Code is available on GitHub.

DownloadCode
 
github

Step 1) Update strings.xml.

Add the below string values to the string.xml located in res ⇒ values ⇒ strings.xml.

Step 2) Create activity_main.xml.

Now create a layout file for the MainActivity.java i.e activity_man.xml and add the below code in your layout file. The code will create an expandable list view for the app.

Step 3) Create layout xml for expandable list.

In order to create a list view, we only need one xml layout files. But for Expandable List View we need two xml layout files. 1st one for list view group item and 2nd one is for list view child item.

1. Now create a layout file for list group i.e list_row_group.xml and add the below code in your layout file.

2. Next create a layout file for list child i.e list_row_child.xml and add the below code in your layout file.

Step 4) Writing the Adapter Class

Now create a package named adapter and create a class named ExpandableListViewAdapter.java and add below code. This class extends BaseExpandableListAdapter and it provides required methods to render listview.

– getGroupView() – Returns view for the list group item.
– getChildView() – Returns view for list child item.





Step 5) Create MainActivity class.

Once you are done with the adapter creation, next create a class named MainActivity.java and add below code. Here i have written the code to populate the expandable list view with data using ExpandableListViewAdapter, initialized the listener for callback of on group expanded, collapsed and on child clicked.

Step 6) Run App

Register the above created MainActivity in AndroidManifest.xml as a main activity and run the app by clicking run button on Android Studio and you will see the UI mentioned above, click on any group item to expand and collapse.

Expandable List View Screen Collapsed


Expandable List View Expanded


Expandable List View Child Clicked

DownloadCode
 
github

Please feel free to comment as well as ask questions. And, yeah! If this post helps you please do share!

Enjoy Coding and Share Knowledge

Show Buttons
Hide Buttons