SimpleExpandableListAdapter With Example In Android Studio

SimpleExpandableListAdapter is an Adapter which is used to map the static data to group and child views defined in an XML (layout) file. We can separately specify the data backing to the group as a List of Map. Each entry in a ArrayList corresponds to one group in the ExpandableListView. The map contains the data for each row.

We can also specify an XML file that defines the views used to display a group, and a mapping from keys in the Map to specific views. This process is similar for a child, except it is one level deeper so the data backing is specified as a List<list>, where the first List correspond to the group of the child and the second List correspond to the position of the child within that group, and finally the Map holds the data for the particular child.

public SimpleExpandableListAdapter (Context context, List<? extends Map<String, ?>> groupData, int groupLayout, String[]groupFrom, int[] groupTo, List<? extends List<? extends Map<String, ?>>> childData, int childLayout, String[] childFrom, int[] childTo)

In Above code snippet we show the implementation of SimpleExpandableListAdapter in Android. Below is the description of all the parameters used for implementation of a SimpleExpandableListAdapter to display ExpandableListView.

Parameters Used In SimpleExpandableListAdapter:

1. context: This parameter is used to pass the context means the reference of current class. this is a keyword used to show the current class reference. We can also used getApplicationContext(), getActivity() in the place of this keyword. getApplicationContext() is used in a Activity and getActivity() is used in a Fragment.

2. groupData: This is a List of Maps. Each entry in a List corresponds to one group. The Maps contain’s  the data of each group and should include all the entries specified in “groupFrom” string array.

3. groupLayout: This parameter is used to set the layout(xml file) for the group items in which you have a TextView, ImageView or any other view.

4. groupFrom: This  is a string array or called a list of column names that will be added to a Map associated with the group.

5. groupTo: The parameter is an integer array used to store the Id’s of the views. The views that should display column in the “groupFrom” parameter. The first N views in this list are given the values of the first N columns in the “groupFrom” parameter.

6. childData: This is a List of Maps. Each entry in a List corresponds to the child of a group. The Maps contain’s  the data for child items and should include all the entries specified in “childFrom” string array.

7. childLayout: This parameter is used to set the layout(XML file) for the child items in which you have a TextView, ImageView or any other view.

8. childFrom: This is a string array or called a list of column names that will be added to a Map associated with the child of a group.

9. childTo: This is an integer array used to store the Id’s of the views. The views that should display column in the “childFrom” parameter. The first N views in this list are given the values of the first N columns in the “childFrom” parameter.


SimpleExpandableListAdapter Example In Android Studio

Below is the example of SimpleExpandableListAdapter in Android where we display an ExpandableListView with Animal and Bird names. In this example we display two group items one is animal and other is birds. Whenever a user click on a group the list expands and displays the child items. It means when a user click on “Birds” the list expands with bird names. In this we implement setOnChildClickListener() and setOnGroupClickListener() events and whenever a user clicks on a child or a group item the name of the item is displayed by using a Toast.

Below you can download complete project code, final output and step by step explanation:

Download Code ?

SimpleExpandableListAdapter Example in Android Studio

Step 1: Create a new project and name it SimpleExpandableListAdapter.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code.

In this step we open an XML file and add the code for displaying a ExpandableListView by using its different attributes.

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ExpandableListView
        android:id="@+id/simpleExpandableListView"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:divider="#f00"
        android:dividerHeight="1dp" />

</RelativeLayout>

Step 3: Create a new XML file for group items Open res -> layout -> group_items.xml and add following code:

In this step we add the code for displaying a TextView for group items.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="55dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="35sp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

</LinearLayout>

Step 4: Create a new xml file for group items Open res -> layout -> child_items.xml and add following code:

In this step we add the code for displaying TextView for child items means for animal and birds names.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/childItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 5: Open src -> package -> MainActivity.Java

In this step we open MainActivity and add the code to initiate the ExpandableListView and add the data to lists for displaying in an ExpandableListView. Finally set the Adapter to fill the group and child data in the list. In this we implement setOnChildClickListener() and setOnGroupClickListener() events. Whenever a user clicks on a child or a group item, the name of the item is display by using a Toast.

package example.abhiandroid.SimpleExpandableListAdapterexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String NAME = "NAME";

    private SimpleExpandableListAdapter mAdapter;
    ExpandableListView simpleExpandableListView;
    // string arrays for group and child items
    private String groupItems[] = {"Animals", "Birds"};
    private String[][] childItems = {{"Dog", "Cat", "Tiger"}, {"Crow", "Sparrow"}};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //  initiate the expandable list view
        simpleExpandableListView = (ExpandableListView) findViewById(R.id.simpleExpandableListView);
        // create lists for group and child items
        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
        List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
        // add data in group and child list
        for (int i = 0; i < groupItems.length; i++) {
            Map<String, String> curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);
            curGroupMap.put(NAME, groupItems[i]);

            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
            for (int j = 0; j < childItems[i].length; j++) {
                Map<String, String> curChildMap = new HashMap<String, String>();
                children.add(curChildMap);
                curChildMap.put(NAME, childItems[i][j]);
            }
            childData.add(children);
        }
        // define arrays for displaying data in Expandable list view
        String groupFrom[] = {NAME};
        int groupTo[] = {R.id.heading};
        String childFrom[] = {NAME};
        int childTo[] = {R.id.childItem};


        // Set up the adapter
        mAdapter = new SimpleExpandableListAdapter(this, groupData,
                R.layout.group_items,
                groupFrom, groupTo,
                childData, R.layout.child_items,
                childFrom, childTo);
        simpleExpandableListView.setAdapter(mAdapter);

        // perform set on group click listener event
        simpleExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                // display a toast with group name whenever a user clicks on a group item
                Toast.makeText(getApplicationContext(), "Group Name Is :" + groupItems[groupPosition], Toast.LENGTH_LONG).show();

                return false;
            }
        });
        // perform set on child click listener event
        simpleExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                // display a toast with child name whenever a user clicks on a child item
                Toast.makeText(getApplicationContext(), "Child Name Is :" + childItems[groupPosition][childPosition], Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }
}

Output:

Now run the App and you will Animal and Birds names listed in ExpandableListView. This we have done using SimpleExpandableListAdapter.

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

Leave a Reply

Your email address will not be published. Required fields are marked *