The ListView is a view group. It helps to displays a list of scrollable items. You can add a text box, check box, images, and other view items to it. In this Android multilevel ListView tutorial you will learn how to add multiple levels to your ListView.

An example of this approach is country, state, and city. Where state comes into existence only when country is clicked. City comes into existence only when state is clicked. Below you can find screenshot of our ListView application.

multilever listview

How to create a multilevel ListView in Android.

We use a linear layout and a ListView to create an Android multilevel ListView.

How to add buttons to a ListView.

A TextView will act as a button. A List will expand on the TextView click event. Add a ScrollView inside the main xml file of your Android application. We are using a linear layout for implementing a multiple level ListView.



Understanding the multiple levels of a ListView

We need to create three separate layouts for our Android multilevel ListView. The first layout is for the parent category. The second layout is for the  sub category. The third layout is for the child item.

android listview details

The First Layout for an Android multilevel ListView

Below is the code of the layout file which will act as a first level for our ListView. We need to add one Textview which will act as a title of one row. We are using an ImageView to display wheather a ListView level is open or not. A View is used as a divider.

You can find images of the ListView arrow buttons below.

arrow down arrow left

Now let’s move to the second level of a ListView. It’s very similar to the first level of a ListView.


Moving to the third level of a ListView

There’re two TextViews to display a name and price of the product. Also the view is used as a divider for our multilevel ListView.

We also need to create three different classes corresponding to these layouts. One each for category, sub-category, and item. In the below java file, you can find code for the three classes. The first class is for the first level. The second class is for the getters and setters sub-category. The third class provides access to the list of available items for our Android multilevel ListView.

Let’s look at the main activity of our Android application.

How do I expand or shrink a multilevel ListView?

By maintaining one Boolean flag. I have used the onTouch() method inside my main activity. Read the code below to handle the onTouch click listener.

What’s next in the Android tutorial series?

You can learn to add multiple columns to a ListView. You can also use JSON to populate a ListView.


Feel free to share your thoughts about this ListView example in the comment section given below. Thank you for reading this example tutorial.