How to create an expandable list view in Android Studio?

Please Share On:

Android ExpandableListView is a view that shows an item in a vertically scrolling two-level list. It is expanding and collapses whenever the user touches on a group item. The top-level list is group items and second-level items are their respective child items.

Today, I am going to show you how to create expandable ListView exactly the same as shown in the below video.

Step to follow:

  1. Create your expandableListView layout in activity_xml file
  2. Create header items layout file and name as header_item.xml
  3. Create Child items layout file and name as child_item.xml
  4. Create a Custom Expandable ListView Adapter in Java class and name as customexpandablelistviewadapter.java
  5. Add some code in your MainActivity.java

Here is a screenshot how your above files look like after being created.

Now let’s start the above steps from 1 to 5.

1) activity_main.xml

Design your expandable listview layout inside this activity_main.xml file. Add the below code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:padding="10dp">

    <ExpandableListView
        android:id="@+id/expListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorAccent"
        android:divider="@android:color/holo_blue_dark"
        android:dividerHeight="1dp"/>

</RelativeLayout>

2) header_item.xml

Create another XML file for your group header titles and name as header_item.xml and add the following code inside it.

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

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textSize="16sp"
        android:gravity="center_vertical"
        android:textColor="@color/black"
        android:text="I am a Header Group Item" />
</LinearLayout>

3) child_item.xml

Create another child layout for child items and name as child_item.xml. Design your child’s layout as you like. Here is a sample of my child_item.xml layout.

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

    <TextView
        android:id="@+id/expandedChildItems"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:textSize="16sp"
        android:gravity="center_vertical"
        android:textColor="@color/black"
        android:divider="@android:color/holo_blue_dark"
        android:dividerHeight="1dp"
        android:text="I am child items" />
</LinearLayout>

4) Custom Expandable ListView Adapter

Create your custom expandable listview adapter and name it as CustomExpandableListViewAdapter.java and extends this adapter from BaseExpandableListAdapter.

Here is a full code of my CustomExpandableListViewAdapter.java class

package com.elsebazaar.myapplication;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

public class CustomExpandableListViewAdapter<S> extends BaseExpandableListAdapter {
    private final Context context;
    private final List<String> headerItem;
    private final HashMap<String, List<String>> childItem;

    public CustomExpandableListViewAdapter(Context context, List<String> headerItem, HashMap<String, List<String>> childItem) {
        this.context = context;
        this.headerItem = headerItem;
        this.childItem = childItem;
    }

    @Override
    public int getGroupCount() {
        return this.headerItem.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return Objects.requireNonNull(this.childItem.get(this.headerItem.get(groupPosition))).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this.headerItem.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return Objects.requireNonNull(this.childItem.get(this.headerItem.get(groupPosition))).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }


    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView) {
        String headerTitle = getGroup(groupPosition).toString();

        if(convertView == null) {

            LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            assert inflater != null;
            convertView = inflater.inflate(R.layout.header_item, parentView, false);
        }
        TextView txtHeader = convertView.findViewById(R.id.title);
        txtHeader.setTypeface(null, Typeface.BOLD);
        txtHeader.setText(headerTitle);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parentView) {
        final String expandedChildList = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            assert inflater != null;
            convertView = inflater.inflate(R.layout.child_item,parentView,false);
        }

        TextView txtChildItems = convertView.findViewById(R.id.expandedChildItems);
        txtChildItems.setText(expandedChildList);

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

}

5) MainActivity.java

Once you have done creating your custom expandable listview adapter. Open your MainActivity.java class and make the changes you have seen in the below code.

package com.elsebazaar.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ExpandableListView;

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

public class MainActivity extends AppCompatActivity {

    ExpandableListView expandableListView;
    CustomExpandableListViewAdapter adapter;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize variable
        expandableListView = findViewById(R.id.expListView);

        // preparing list data
        prepareListData();

        adapter = new CustomExpandableListViewAdapter(this, listDataHeader, listDataChild);

        expandableListView.setAdapter(adapter);
    }

    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add("Fruits");
        listDataHeader.add("Vegetables");
        listDataHeader.add("Meats");
        listDataHeader.add("Drinks");

        // Adding child data
        List<String> Fruits = new ArrayList<String>();
        Fruits.add("Apples");
        Fruits.add("Bananas");
        Fruits.add("Mangoes");
        Fruits.add("Pineapples");
        Fruits.add("Watermelon");
        Fruits.add("Dragon Fruits");
        Fruits.add("Kiwi");

        List<String> Vegetables = new ArrayList<String>();
        Vegetables.add("Cabbage");
        Vegetables.add("Brussels Sprouts");
        Vegetables.add("Carrots");
        Vegetables.add("Collard Greens");
        Vegetables.add("Eggplant");
        Vegetables.add("Cauliflower");

        List<String> Meats = new ArrayList<String>();
        Meats.add("Beef");
        Meats.add("Lamb");
        Meats.add("Veal");
        Meats.add("Pork");
        Meats.add("Kangaroo");

        List<String> Drinks = new ArrayList<String>();
        Drinks.add("Coca Cola");
        Drinks.add("Fanta");
        Drinks.add("Sprite");
        Drinks.add("Soda");
        Drinks.add("Lemonade");

        listDataChild.put(listDataHeader.get(0), Fruits); // Header, Child data
        listDataChild.put(listDataHeader.get(1), Vegetables);
        listDataChild.put(listDataHeader.get(2), Meats);
        listDataChild.put(listDataHeader.get(3), Drinks);

    }
}

Output:



You may be interested in the following topics:

Leave a Reply

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

Copyright @2023. All Right Reserved.


Social media & sharing icons powered by UltimatelySocial