Custom Expandable ListView – Android


Custom Expandable ListView – Android

Android has its own expandable listview ready-to-use but if you want to create your own expandable listview, follow this tutorial. All items will be read from a .txt file which contains a tree in form of Json.

Add .txt file to assets folder. If there is no assets folder in your project, you can add it by clicking File>New>Folder>Assets Folder.

The idea is that adding-removing lists to expand a list item. When you click on a list item:
*If item has at least one child and already expanded, then collapse it,
*If item has at least one child and collapsed, then expand it,
*Otherwise, do nothing.

Also, we have navigation buttons to move next item and previous item.

Let’s start with layout. We need a TextView to show current item label, a RecyclerView to list items and two buttons for navigation. Open activity_main.xml.

We also need a layout for list item which has a TextView for item label and an ImageView for “+,-” icons. Create an XML file named item_list.xml.

That’s all for layouts. You can define some colors. Before start coding, open app level gradle file and add these two libraries:

We will use RecyclerView library for list and Gson library for parsing .txt file.

Item class contains id, title, child list, isExpanded, isSelected and hierarchy fields.

Creating a constant class may help you to get constant variables easily. We will define navigation constants and indent values in this class.

Now, just think about what we need for listing all items. Create a java class named ItemRWAdapter. We will handle changing of icon and background color.

Now open MainActivity.java and write the code below.

You can find this project files on Github. Ask your questions as comment this page.

 

 

©Coffee Break Codes – Custom Expandable ListView – Android