Expandable list view is used to group list data by categories. It has the capability of expanding and collapsing the groups when user touches header.

If you are not aware of list view before please refer to this tutorial Android ListView Tutorial

Download Code
This image is for thumbnail purpose only
android expandable list view

Let’s start by creating a new project..

1. Create a new project in the Eclipse IDE from File ⇒ Android Application Project and fill all required details. I left my main activity name as MainActivity.java

2. In order to create an expandable list view, we need three xml layout files. First one is for main listview, 2nd one for list view group item and 3rd one is for list view child item. Open your activity_main.xml and add ExpandableListView element.

<?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="fill_parent"
    android:orientation="vertical"
    android:background="#f4f4f4" >

            <ExpandableListView
                android:id="@+id/lvExp"
                android:layout_height="match_parent"
                android:layout_width="match_parent"/>   

</LinearLayout>

3. Create another xml layout for list view group header. I created an xml file named list_group.xml and pasted following code.

<?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="wrap_content"
    android:orientation="vertical"
    android:padding="8dp" 
    android:background="#000000">


    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textSize="17dp"
        android:textColor="#f9f93d" />

</LinearLayout>

4.Create one more xml file named list_item.xml for child list item. This will contain simple TextView element.

<?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="55dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="17dip"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

</LinearLayout>

5. I am using a custom adapter class to create list view. Create a new class file called ExpandableListAdapter.java and extend this from BaseExpandableListAdapter. This class provides required methods to render listview.

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

package info.androidhive.expandablelistview;

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

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;

public class ExpandableListAdapter extends BaseExpandableListAdapter {

	private Context _context;
	private List<String> _listDataHeader; // header titles
	// child data in format of header title, child title
	private HashMap<String, List<String>> _listDataChild;

	public ExpandableListAdapter(Context context, List<String> listDataHeader,
			HashMap<String, List<String>> listChildData) {
		this._context = context;
		this._listDataHeader = listDataHeader;
		this._listDataChild = listChildData;
	}

	@Override
	public Object getChild(int groupPosition, int childPosititon) {
		return this._listDataChild.get(this._listDataHeader.get(groupPosition))
				.get(childPosititon);
	}

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

	@Override
	public View getChildView(int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {

		final String childText = (String) getChild(groupPosition, childPosition);

		if (convertView == null) {
			LayoutInflater infalInflater = (LayoutInflater) this._context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infalInflater.inflate(R.layout.list_item, null);
		}

		TextView txtListChild = (TextView) convertView
				.findViewById(R.id.lblListItem);

		txtListChild.setText(childText);
		return convertView;
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return this._listDataChild.get(this._listDataHeader.get(groupPosition))
				.size();
	}

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

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

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

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		String headerTitle = (String) getGroup(groupPosition);
		if (convertView == null) {
			LayoutInflater infalInflater = (LayoutInflater) this._context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = infalInflater.inflate(R.layout.list_group, null);
		}

		TextView lblListHeader = (TextView) convertView
				.findViewById(R.id.lblListHeader);
		lblListHeader.setTypeface(null, Typeface.BOLD);
		lblListHeader.setText(headerTitle);

		return convertView;
	}

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

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

6. Once you are done with customer adapter, open your MainActivity.java and do the following changes. In the following I created required data needed for list view and passed it to custom adapter.

package info.androidhive.expandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

public class MainActivity extends Activity {

	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
	List<String> listDataHeader;
	HashMap<String, List<String>> listDataChild;

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

		// get the listview
		expListView = (ExpandableListView) findViewById(R.id.lvExp);

		// preparing list data
		prepareListData();

		listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

		// setting list adapter
		expListView.setAdapter(listAdapter);
	}

	/*
	 * Preparing the list data
	 */
	private void prepareListData() {
		listDataHeader = new ArrayList<String>();
		listDataChild = new HashMap<String, List<String>>();

		// Adding child data
		listDataHeader.add("Top 250");
		listDataHeader.add("Now Showing");
		listDataHeader.add("Coming Soon..");

		// Adding child data
		List<String> top250 = new ArrayList<String>();
		top250.add("The Shawshank Redemption");
		top250.add("The Godfather");
		top250.add("The Godfather: Part II");
		top250.add("Pulp Fiction");
		top250.add("The Good, the Bad and the Ugly");
		top250.add("The Dark Knight");
		top250.add("12 Angry Men");

		List<String> nowShowing = new ArrayList<String>();
		nowShowing.add("The Conjuring");
		nowShowing.add("Despicable Me 2");
		nowShowing.add("Turbo");
		nowShowing.add("Grown Ups 2");
		nowShowing.add("Red 2");
		nowShowing.add("The Wolverine");

		List<String> comingSoon = new ArrayList<String>();
		comingSoon.add("2 Guns");
		comingSoon.add("The Smurfs 2");
		comingSoon.add("The Spectacular Now");
		comingSoon.add("The Canyons");
		comingSoon.add("Europa Report");

		listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
		listDataChild.put(listDataHeader.get(1), nowShowing);
		listDataChild.put(listDataHeader.get(2), comingSoon);
	}
}

Run your project, you should see following output. (Note: The list view group indicators might change depending upon your android version)

android expandable list view

ListView child item click listener

Detecting the child item click can be done by implementing setOnChildClickListener listener on listview.

// Listview on child click listener
		expListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				Toast.makeText(
						getApplicationContext(),
						listDataHeader.get(groupPosition)
								+ " : "
								+ listDataChild.get(
										listDataHeader.get(groupPosition)).get(
										childPosition), Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		});

Listening when group is expanded

You may want to execute some lines of code when the listview group is expanded. For this you can use setOnGroupExpandListener which triggers an event when listview group expanded.

		// Listview Group expanded listener
		expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Expanded",
						Toast.LENGTH_SHORT).show();
			}
		});

Listening when group is collapsed

Implementing setOnGroupCollapseListener will trigger an event when listview group is collapsed.

		// Listview Group collasped listener
		expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

			@Override
			public void onGroupCollapse(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Collapsed",
						Toast.LENGTH_SHORT).show();

			}
		});

Complete Code

Here is the final code for MainActivity.java

package info.androidhive.expandablelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

public class MainActivity extends Activity {

	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
	List<String> listDataHeader;
	HashMap<String, List<String>> listDataChild;

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

		// get the listview
		expListView = (ExpandableListView) findViewById(R.id.lvExp);

		// preparing list data
		prepareListData();

		listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

		// setting list adapter
		expListView.setAdapter(listAdapter);

		// Listview Group click listener
		expListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// Toast.makeText(getApplicationContext(),
				// "Group Clicked " + listDataHeader.get(groupPosition),
				// Toast.LENGTH_SHORT).show();
				return false;
			}
		});

		// Listview Group expanded listener
		expListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Expanded",
						Toast.LENGTH_SHORT).show();
			}
		});

		// Listview Group collasped listener
		expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {

			@Override
			public void onGroupCollapse(int groupPosition) {
				Toast.makeText(getApplicationContext(),
						listDataHeader.get(groupPosition) + " Collapsed",
						Toast.LENGTH_SHORT).show();

			}
		});

		// Listview on child click listener
		expListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(
						getApplicationContext(),
						listDataHeader.get(groupPosition)
								+ " : "
								+ listDataChild.get(
										listDataHeader.get(groupPosition)).get(
										childPosition), Toast.LENGTH_SHORT)
						.show();
				return false;
			}
		});
	}

	/*
	 * Preparing the list data
	 */
	private void prepareListData() {
		listDataHeader = new ArrayList<String>();
		listDataChild = new HashMap<String, List<String>>();

		// Adding child data
		listDataHeader.add("Top 250");
		listDataHeader.add("Now Showing");
		listDataHeader.add("Coming Soon..");

		// Adding child data
		List<String> top250 = new ArrayList<String>();
		top250.add("The Shawshank Redemption");
		top250.add("The Godfather");
		top250.add("The Godfather: Part II");
		top250.add("Pulp Fiction");
		top250.add("The Good, the Bad and the Ugly");
		top250.add("The Dark Knight");
		top250.add("12 Angry Men");

		List<String> nowShowing = new ArrayList<String>();
		nowShowing.add("The Conjuring");
		nowShowing.add("Despicable Me 2");
		nowShowing.add("Turbo");
		nowShowing.add("Grown Ups 2");
		nowShowing.add("Red 2");
		nowShowing.add("The Wolverine");

		List<String> comingSoon = new ArrayList<String>();
		comingSoon.add("2 Guns");
		comingSoon.add("The Smurfs 2");
		comingSoon.add("The Spectacular Now");
		comingSoon.add("The Canyons");
		comingSoon.add("Europa Report");

		listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
		listDataChild.put(listDataHeader.get(1), nowShowing);
		listDataChild.put(listDataHeader.get(2), comingSoon);
	}
}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • baha_odeh

    first comment , thank you

    • Third comment ….. you are welcome 🙂

      • Siddhu Vydyabhushana

        forever comment @ravi8x:disqus is great great great …

  • Balakrishnan

    HI Ravi..i understood this example..How can i add Edittext an Button in childview?

    • You can add them in list_item.xml file

      • Lorenzo Volponi

        yes but..when in the adapter i set the listener it wont listen!!! you know why?

  • Filipe Tagliacozzi

    Ravi… excellent work… Anyone can make great apps relying on codes presented here. Through people like you we will be increasing the overall quality of android apps. I particularly have a easier learning when altering ready codes and making changes to see the behavior .. Congratulations…. I will click all the sponsors that I can.

  • saladi krishna chaitanya

    Hi ravi u r doing a great job. Its very helpful for every one start doing their apps.
    Try to update daily one concept even it is small also no problem.It will also be helpful for someone..Keep doing.

  • LloydBlv

    Thanks,But how to anmiate expand and collapse?

    • ‘e’

      Any way to animate expanding the list items?

  • Excellent explanation, thanks 😉

  • james

    Thank you for the tutorail, God bless you

  • Ines Belhouchet

    Parfait :))))

  • Ramiz Mohamed

    As good as always, well done.

  • Ayush

    Hey can u add the code to “auto close the all previous opened list and only opens the currently expandable list “??

  • vignes

    wow.. wow wow.. what an excellent tutorial..

  • Chinthaka Devinda

    Great Work Ravi this is really helpful thanks 🙂

  • Katia Zanotti

    Hi, your tutorial is great!

    but when I run the project it doesn’t show the indicators.
    If I try to click the header this action generate the following error:

    Unexpected error while launching logcat. Try reselecting the device.] device not found
    com.android.ddmlib.AdbCommandRejectedException: device not found
    at com.android.ddmlib.AdbHelper.setDevice(AdbHelper.java:752)
    at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:373)
    at com.android.ddmlib.Device.executeShellCommand(Device.java:462)
    at com.android.ddmuilib.logcat.LogCatReceiver$1.run(LogCatReceiver.java:109)
    at java.lang.Thread.run(Thread.java:724)

    any help?
    Thanks

    • Ben

      Seems like your device is not detected by your Operating system,try to install appropriate device drivers first

  • Nishu

    Sir ! i wana get record from data base ,how can i?

  • how to start new activity in child data using expandablelist.?

  • Beatriz Hernández

    Dear Ravi,

    My name is Beatriz Hernández and I get in touch
    with you because we are developing an advertising campaign which we would like
    to count on you.

    If you are interested , please write me
    back and I will tell you more about the project.

    Best regards,

    Beatriz

  • Kunwar Abhishek

    Hey Ravi
    I want to add an element in expandable list
    as we do in listview by using adapter.addall(arraylist)
    how to perform this in Expandable list view

  • Công Bình Trần

    thank you!

  • Sk Ahmed Hossain

    awesome awesome awesome……………………

  • Fernando

    Excellent tutorial! Is just what I was looking for, I want to modify a bit your listview, I pretend to put some buttons in the listview or set an onclick event, Could you help me with that? I need to develop a menu for a restaurant and it’s necessary for me that the program counts the clicks on each product. I hope you can help me with this task .

  • akhil nair

    Hey Ravi good tutorial i want to know how to create ExpandableListView with image and text else a coustom ExpandableListView

    Thank You

  • Andy

    how to set onClickListener(intent) for any particular child option

  • rahul

    nice tutorial..please keep it up…

  • Angel

    Hi!

    First, thank you for a very great tutorial. As a beginner in Android, you have been a great help to me.

    I am currently trying to make your program into a dynamic expandable listview with data coming from a remote server accessed through PHP and JSON (using your other tutorial as reference). However, I’m having problems trying to save the data on the listDataHeader and listDataChild. Could you please share some tips on how to resolve it?

    Thanks again and more power!

  • Joseph

    hi, what if I there is a add button? do you have source code for this? thanks a lot! 🙂

  • sravani

    hi nice blog spot , how to implent Expandable List view up to Four levels

  • Daan Dawud

    Fantastic dude! Im going to attempt to use this with the Navigation drawer. Hopefully it shouldn’t be too bad.

  • Mike

    Ravi => Android Sensei !!!

  • Der Ääl

    1st thing: great work, thank you so much!
    2nd thing: i tried to put a 2nd textview into my childrow.xml but it doesn’t work. i think i’ve made a mistake in the getChildView or in prepareListData… can you (or maybe anybody else) please help me?
    would be great!
    thank you

  • MrBoomBostic

    “No Empty Constructor” ???

  • Helmer Plaza

    Hi..how do i apply this on a fragment?? where do i put it?on the onCreate or onActivityCreated?

  • mike20122012

    Awesome tutorial..:)..This really helps a lot.
    How can I implements this when using fragments? Help would be really appreciated..:)

  • Ashish

    Very useful article but there is one problem in each article. Problem is that the width of code box is very less so we have to scroll horizontally again and again. so please make it wider if possible

  • systemz

    The best tutorial !!
    When i scroll the list item i have a white background. To fix it add the following attribute android:cacheColorHint=”#00000000″ in the xml file : activity_main.xml in ExpandableListView view

  • Lisa

    How can you add a third level to this? All of the other examples use a completely different form.. this is the best one, but need to add a 3rd level

  • Jean Hewetson

    hardcoded values into expandablelistview. I want to know how do you get generic database values into it?

  • sasa

    I stuck badly in my code to implement ExpandableListView and your code can help me A LOT,but when I try your code it gives me an error in this part:
    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    which the error is “Cannot instantiate the type ExpandableListAdapter”
    could you please help me to solve it?
    Thanks a lot

    • Naganji Polam

      same error i’m also getting now.

      • Furkan Kurt

        Yes, same error i’m also getting now. But, I don’t find it 🙁

        • Furkan Kurt

          Hey, I find it 🙂 you make a class by “ExpandableListAdapter” name.
          This class is adapter class 🙂

    • GokulakrishnanM

      Change the class name
      “ExpandableListAdapter” to some other. Android have interface class in this name…

  • Naganji Polam

    Hi, The best tutorial.

    I like your tutorials.

    I’ve a small doubt, you actually used same image for all list items. But, how to add diff images for list items.

    And one more is , can you implement some non expandable list items and some expandable list items like this

    http://i.stack.imgur.com/vilHb.png

    Thanks,

    Siva

  • Naganji Polam

    Hi Sasa,

    I also get the same error, but finally solved.

    Just change that a line as

    listAdapter = new packageName.ExpandableListAdapter(this, listDataHeader, listDataChild);

    instead of listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Thanks,
    Siva

  • needhelp

    Hi,

    Nice tutorial thankyou but how do i add a second textview to the childview.I mean adding it is easy (you just have to edit the XML) but i don’t understand how to set the adapter to make text appaer in the second textview.

    • systemz

      I want a second childview too and a textview in every group please…

  • amala ray

    Hey nice tutorial, can you tell me how to add empty views as children of every listview element. So that when i click on an item which does not have children, the application does not crash.

  • Abdullah

    Thank a lot for this codes, works perfectly, it was soooo helpful for me, I was desperately looking for codes, thanks again. 🙂

  • Senjo

    Thanks a lot.

  • ALB

    Thanks for this super helpful tutorial!! For those asking about putting in a fragment, I managed to get that working, so thought I would share: (1) fragment extends ListFragment, (2) create a new layout for the fragment with same code as described above for activity_main.xml except change to “android:id=@android:id/list” and inflate this layout in onCreateView in the fragment (3) put this in onActivityCreated:

    expListView = (ExpandableListView) getListView();
    prepareListData();
    adapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
    expListView.setAdapter(adapter);

    • an

      Thanks so much, you are a lifesaver!

      • Guest

        I dont understand what number 3 is, where is it being added exactly? in OnCreate of the Activity that the frag is being created from?

  • Riadh Karchoud

    How can i take off the arrow on the left (the one that indicates if the list is expanded or not ) .. i created my own arrow on the right that’s why i wanna take off the one on the left !!

  • Shubham Singh

    is it possible to collapse items other than the clicked one

    • Rishil

      Do you want to expand and collapse all the items at once ?

      • Shubham Singh

        nope to collapse other groups when a group is clicked. ie expand the clicked and collapse the others.

        • Rishil

          Hello Shubham,

          Try this code. It worked for me.

          private int lastExpandedPosition = -1;
          private ExpandableListView lv; //your expandable listview

          lv.setOnGroupExpandListener(new OnGroupExpandListener() {

          @Override
          public void onGroupExpand(int groupPosition) {
          if (lastExpandedPosition != -1
          && groupPosition != lastExpandedPosition) {
          lv.collapseGroup(lastExpandedPosition);
          }
          lastExpandedPosition = groupPosition;
          }
          });

          • Shubham Singh

            thanks mate it worked well

          • Rishil

            Your welcome buddy…

            But there is one problem when changing the orientation.
            Follow this step to reproduce it :
            keep one tab expanded. Now change the orientation of your phone.
            Now try to expand another tab. So it won’t collapse the previously selected tab and. So at a time 2 tabs will be expanded….lol

  • Rishil

    @ravi8x:disqus : How can i implement Search filter Functionality to Expandable listview. ?

  • Замира Норова

    Guys, i have a problem on lines

    drawerListView = (ExpandableListView) findViewById(R.id.left_drawer);
    listAdapter = ExpandableListAdapter(MainActivity.this, listDataHeader, listDataChild);
    drawerListView.setAdapter(listAdapter);

    error is “The method setAdapter(ListAdapter) in the type ListView is not applicable for the arguments (ExpandableListAdapter)”. What i’m doing wrong?

    • systemz

      “New” is missing after “listAdapter =”

  • Richard

    Ok so after taking a good look on this one I was wondering if we could integrate this project on the Drawer navigation. Like for example; we have five default items on the drawer navigation and below that are set of expandable items. Hey Ravi is that possible to integrate this in a Drawer Navigation? I mean both of them are list views right?

  • Ivelfan

    Awesome article !

    Many thanks !

  • Harish

    Hi
    I want to do expandable listview like tree view..
    It is possible to do?

  • prabhakaran

    very nice tutorial………. but i want, if suppose open a group once at a time, other groups are collapse

  • Tharaka Nirmana

    Thanks a lot, great tutorial. After 2 days of research this tutorial helped me to get what I want finally. Thank you!

  • Sohail Zahid

    Again Thanks A lot Ravi………..

  • Nadir Ali

    brilliant code to help me, and solve the problem

  • Developer

    How do i insert a radio button in the child item of the list view?

  • Guest

    Hi Ravi, Thanks for this, how can I put subtitle in the parent header?

  • Aj

    Hi Ravi, Thanks for this, how can I put subtitle in the parent header?

  • Illuminate

    how would i open the list item up in a fragment, or another window, where it would display images and possibly a write up

  • JP

    Great tutorial..How could you add checkboxes to the children?

  • Luis Alberto Romero Calderon

    Awesome tutorial. very clear. Thanks

  • Pradeep

    This is great…. Very clear and usefull items, Thanks much for doing this….

  • silver

    I have tried to use a EditText inside ExpandableListView but after adding this Group is not expanding on click. Anyone has any idea about this?

  • Gold

    $(“article”).css(“width”,”1000px”);
    Run this in the browser’s dev tools to expand the article’s width. Easier to read code this way.

  • Vick

    Trying to hide and embed the database primary key behind the values that are being used to populate the children data. Want to create and Edit item page similar to how you did on list view. How do I store and send that?

    • Vick

      Answered my own question. Do it all in your getChildView

      @Override

      public View getChildView(int groupPosition, final int childPosition,

      boolean isLastChild, View convertView, ViewGroup parent) {

      final String childText = (String) getChild(groupPosition, childPosition);

      if (convertView == null) {

      LayoutInflater infalInflater = (LayoutInflater) this._context

      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      convertView = infalInflater.inflate(R.layout.list_item, null);

      }

      String SubChildText = childText.substring(childText.lastIndexOf(“—“) + 3);

      String SubChildTextID = childText.substring(0,childText.lastIndexOf(“—“));

      TextView txtListChild = (TextView) convertView

      .findViewById(R.id.lblListItem);

      TextView txtListChildID = (TextView) convertView

      .findViewById(R.id.pid);

      txtListChild.setText(SubChildText);

      txtListChildID.setText(SubChildTextID);

      return convertView;

      }

  • Kiba

    if i want to display a JSONArray, what would be the code?

    • Kiba

      i’m starting to code on android

      • Peter Mageto

        Hi Kiba…did u manage to post using JSONArray? please assist

  • Siavash

    hi,ihave a problem with id : “id cannt be resolved or is not a field “

  • sravan

    thanks it was nice post , helped me a lot 🙂

  • Hi I have a problem
    When I open a new page when I click on a child, not a tost

  • izzy

    i click on a child and dont get a toast, anyone knows why?

    • Brandon

      You need to put the code blocks:

      // Listview on child click listener
      expListView.setOnChildClickListener(new OnChildClickListener() { … }

      WITHIN the “onCreate(…)” method. Then they will run properly (import the proper functions that eclipse says or do a Ctrl+shift+O and it will import the necessary files.

      But put those 3 listener methods with the toasts functions in the onCreate function.

  • Peter Mageto

    Ravi, Guys…please assist. I need to use JSON approach to fetch my parent and child nodes. Please assist…

    • Coder

      Hi, had you solve this problem please ?? i need it . Please assist

  • Brad

    Another great tutorial. Thanks!

  • Brandon

    I just want you to know, that after hours of looking for a tutorial on how to do this.. I finally navigated back to you, my default android tutorial man… and my god. Your code is beautiful, it’s explanations are great and its easy to follow. THANK YOU SIR.

  • amit

    Nice Tutorial Thanx

  • Suare

    Nive Tutorial man! I implemented it with Fragments

  • Lisa

    You are a good writer. Clear and straight to the point tutorials. You should compile all your work into a book. Be blessed.

  • Fedro

    Thanks for this. You are a good programmer and an excellent teacher. Your tutorials are very clean and easy to understand.
    Has anyone an example of how to implement ExplandableListview retrieving data from a JSON array?
    I suppose that it will be useful if update this example explaining how to work with dynamic data.

  • JJ

    Hi, can I do multiline textview for children?
    Thanks

  • Hung Tran

    i don’t see icon of expand listview?

  • anusha

    can u tell me how to make auto close of one list when other one is clicked…..

  • Juwar74

    Can you extend this article to include moving to another screen when one of the children are clicked. I’m not sure how that works actually. I would need it to move to another screen

  • Hardik Trivedi

    Thanks a ton.. It helped me a lot!!

  • Kalu Khan Luhar

    Thanks Ravi , your tutorials helped me a lot. One question is that how to expend/collapse list with smooth animation.

  • Krits

    Hello and thanks for the nice tutorial! I am using this layout for a project and I am experiencing a problem! I have managed to change the background colour of each parent(and child) to transparent but when I click on the parent(or the child) I am getting that yellowish colour(only during the click) which doesn’t match the blue theme of my app. I’ve searched everywhere and cannot find how to change it to transparent as well. Any help would be much appreciated!

  • Wasim Amin

    @Krits: use this in your listview
    android:cacheColorHint=”@android:color/transparent”

  • Vladimir Topalovic

    hi Ravi. I am looking to learn how to use expanable list, for some time and this exampe is the best one, that i can find on net. Can you please help me?

    for a week i am trying to animate expand and colapse for Expandable list and i done all exept for moment when auto-scroling is activated. when i expand list on bottom off screen, list auto-scroll on bottom of group and it totaly mess my animation. how can i stop that auto-scroll. I alredy tryed android:transcriptMode and setTranscriptMode(0). Please help me i do not have any other way of reseach it more.

  • Sino

    how can i set images to parents and childs?

    • Guest

      To add images to either parents or children or both you would have to add an ImageView into their respective xml layout files – list_group.xml for parents, list_item.xml for children.
      Here don’t forget to use margins to place the image where you need it.
      You can also place a drawable in the xml thus making all your items have the same images. Alternatively, you could assign image resources to each through code, which might add a little more flavour to your project, but is more involving.
      Good Luck!

  • Jake

    how to parse names from json file to expandable list? thanks.

  • saravanan

    How to give scroll to group items instead of whole exapndable listview

  • Anon

    I keep getting, “ExpandableListAdapter” is abstract can’t be instantiated. On this line, “listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);” Any solutions?

    • Sam Soo

      How do you declare your Adapter class? i declare my as below

      public class MenuExpandableAdapter extends BaseExpandableListAdapter {

      Notice its, BaseExpandableListAdapter

    • Shuvo Joseph

      Your Fragment is importing android.widget.ExpandableListAdapter, Remove that.
      First create the class ExpandableListAdapter then Write
      ExpandableListAdapter listAdapter;
      listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
      May be Class ExpandableListAdapter is clashing with interface android.widget.ExpandableListAdapter or change the name of the class ExpandableListAdapter to something else.

  • nishant

    #Help

    Hello friends , can any one tell me how to add expandable list view in existing fragment(As in case of Navigation drawer I’ve fragment class ).Do I need to create new activity or can I add the above MainActivity code to
    the existing fragment class.

    • Aleksandar Petrovic

      Incorporating this into your project will not be as straight forwards as simply pasting the code into your fragment.
      You need to create the class, per Ravi’s example. Once you have the class made, you can then add the listeners from his MainActivity into your fragment. Do note because Ravi extends an activity and not a fragment there will be some minor changes that you will have to handle. This is not hard and the errors should clue you in as to what changes have to be made.
      (Hint: in the listadapter line instead of ‘this’ you will most likely need to replace it with ‘getActivity()’) or something to that effect.

  • Aleksandar Petrovic

    Thank you for this wonderful project! It works like a charm!
    I added a bit I found that I wanna share:
    public void onGroupExpand(int groupPosition) {
    int len = listAdapter.getGroupCount();

    for (int i = 0; i < len; i++) {
    if (i != groupPosition) {
    expListView.collapseGroup(i);
    }
    it will allow for one group to collapse as another is clicked to expand!
    Sweet functionality!

  • Hanu

    I want to declare two dates like start date and end date in one list view,how to declare?

    • Sam Soo

      put 2 TextView in your Item Layout and name them like tvStartDate and tvEndDate,

      in Adapter, get them with

      TextView tvStartDate = (TextView)convertView.findViewById(R.Id.tvStartDate);

      TextView tvEndDate = (TextView)convertView.findViewById(R.Id.tvEndDate);

  • ahtsham

    i want a button in group_item.xml class.listview should expand when i press the button not by clicking the listrow.i added my button in xml but dont know how to set clicklistener.kindly help me by writing code…..

  • Prasanna Kumar

    Thanks buddy…it helped me alot..

  • Alex Monari

    Awesome .. super helpful !!!!!

  • Clay Martin

    Great job. Very helpful to get my exandablelistview up and running.

  • Alireza saemi

    thanks man , 🙂
    do u think we can have exandable list inside navigation drawer ?

    • Edu App

      yep surely.

      • Alireza saemi

        Can u do us great favour and learn us how to do it ? Sry if im asking alot .

  • wade

    thanks

  • Abdoul Doulab

    hi! ravi thanks for this… i want add a checkbox on Group and child and when i select checkbox Group all the checkbox child will be selected… Thans again…

  • fuck me too

    I love Android HIVE. Helped me many times! Keep on this good work.

  • Sudheesh Mohan

    Hey if therre are 10 headings, do we need to create 10 arraylists? Is there any way to avoid this?

  • Ferry Fernandez

    Hi Ravi,
    1. i add CheckedTextView, to childlistitem. how to make it checked onchildclick?
    2. i need to change the header group label when onchildclick?

    can anyone tell me how to do ?

  • Mahmoud Badr

    انت جامد فشخ 😀

  • hackerGK

    It working nice 🙂 thanks

  • Jonathan

    It doesn’t work for me, I have a trouble in this line

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Exactly in ExpandableListAdapter, it says it cannot be instantiate.

    • Jonathan

      I’ve already read the comments and I found the solution, now it works good!!

      Thank you so much!!

      • Riddhi Patel

        if you got solution thn pls kindly inform me bcs i also get same trouble in

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

  • SparkleIshan

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    Error:(35, 23) error: ExpandableListAdapter is abstract; cannot be instantiated

  • Siva Bala

    Hi thanks for ur code. I need to navigate to another page when child item is clicked. Can any one help me plz??

    • Guest

      Same question . Please if you found a solution let me know and vice versa if a found a solution i will tell you .

    • mohamed

      // Listview on child click listener
      expListView.setOnChildClickListener(new OnChildClickListener() {

      @Override
      public boolean onChildClick(ExpandableListView parent, View v,
      int groupPosition, int childPosition, long id) {
      /*
      // TODO Auto-generated method stub
      Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition)
      + ” : “+ listDataChild.get(listDataHeader.get(groupPosition))
      .get(childPosition), Toast.LENGTH_SHORT).show();
      */
      switch (childPosition) {

      case 0:
      mycostumeactivity();

      break;
      case 1 :

      Intent a = new Intent(getApplicationContext(), AboutActivity.class);
      startActivity(a);
      break;

      case 2 :

      break;
      case 3 :

      break;
      case 5 :

      break;

      }

      return false;

      }
      });
      }

      • Siva Bala

        Thanks a lot #Mohamed

      • nasznjoka

        what if i dont know the number of child items how select them dynamically without using switch

        • mohamed

          Sorry for late reply but hope this will help you

          Use something like that

          // Listview on child click listener
          expListView.setOnChildClickListener(new OnChildClickListener() { @Override
          public boolean onChildClick(ExpandableListView parent, View v,
          int groupPosition, int childPosition, long id) {
          switch (groupPosition) { // Expandable parent 1
          case 0:
          Intent i = new Intent(this, LastActivity.class);
          i.putExtra(“position”, childPosition);
          startActivity(i);
          break
          case 1:

          break

          }

          In LastActivity.java
          Get extra and go

          • nasznjoka

            thanks but i already finished that project and I decided to activate onlick on an entire row but i got a new project which i think such functionality is required(clicking on list item child views) I’ll check on it thanks

  • R

    how do i customise the listview? i want to change the colour and background of the listdataheader

  • Eduardo

    the list indicator are not displayed in api 10. How do I solve it?

  • Luzi

    Hey ! Thanks a lot for this example ! I used it for my application and it works fine 🙂

    But (there is alway a but 😀 ), I would like to implement a filter only on the Header Datas, but I don’t know how. I tried different code founded on the web, and adapted it to my code, but it didn’t work.

    Can you help me, please ?

    Thx, Nico 🙂

  • arun

    Nice Example.. Thanku.. I need show some items (for example 2) on collapse instead hiding all items. What to do?

  • yash sharma

    Its not Working for me the logcat says “Your Content must have listView”

  • J Bala Prakash

    how to use expandable view in sqliet db help me…..

  • Vijayadhas

    Hai.. Is there any example for sliding menu with expandable view??

  • rahul

    how can i do same thing when click on slidenavigation menu after that i want to see expandable view

  • Bharath Reddy

    Excellent.thanks

  • manvi gautam

    heyyyy .. i wannna use multi line text how can i use in this …
    GA-KHYIL HOUSE

    2-3Fl.House No.39, Block-12 , New Camp, New Aruna Nagar, Majnu Ka tila, Delhi-110054, India

    Tel: 0091-11238-111-47

    Fax: 0091-11-238-111-49
    how to use this under a single header….
    plzz rply asap …..
    thankssss a lot in advance

  • ancy

    hi wan know is that possible to expand child data ?

  • Sivan Kumar

    Thanks … Good Work

  • Salman Mohammed

    Is it possible to add children strings from (R.string) or Arrays(R.array) in order to support other languages, instead of using (” “)?

  • Văn Lý Vũ

    Thanks for this post, it’s very helpful. I did it and it worked. But i want to extend a little bit. That i want to add a footerView to childView. Now what i do is:
    1. I create a layout file name footer_view.xml
    2. Then for each parent item, i add one more element to listChild.
    3. In getChildView method, i check
    if (childPosition == getChildrenCount(groupPosition) – 1){

    //render footerView here
    }else{
    //render normal child item
    }

    But seem it doesn’t work. When i click the parent first time, it works, but the second time it show error: NullPointerException.
    Did i do anything wrong?
    Thanks for your time.

  • ati’atul maula

    It’s good tutorial. I have trouble to make arrow icon on ExpandableListview, I have used android:groupIndicator but the image result is too large. Can you tell me how to set height and width it?

    Thanks for your time.

  • vahid

    One of the best tutorials ever

  • Ancy Murikupudi

    can we do multi-layered expandablelistview with Json response array data.?

  • Steve

    Why are you mixing fill and match_parent that often?

  • jayant rawat

    What to do if data is coming through json please suggest me

  • Ion Popescu

    I followed the “How to connect Android with PHP, MySQL” tutorial. I successfully populated a database with some test values. Now I need to make a list like this above, with “name” as List header, and ‘price” and “description” as Child, (to appear when I touch the “name” and list is expanded). I preserved tags from the other tutorial, so it will be more clear what i want to achieve. I am a very beginner at android, so I have no idea how to fetch those data, and populate the list with all the names, prices, etc. Can someone help me? 🙂

  • Animis

    how do I add a LongClick listener to the Group and CHildren? I want to be able to add items to the list by long clicking on the group and then typing something in

  • Aayushi

    hey hi ,Android hive is a great site.Hats off to writer.
    I made the expandable list view acc to your tutorial but what i have to do if I want to populate Expandable List View with values from database?Means what changes I have to do in MainActivity.java add() .Will be of great help.Waiting for your reply

  • Mike

    @Override
    public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
    .size();
    }

    How does this work? Doesn’t get() take in an int?

  • Prajwal

    How to add onClick to items inside the row.
    for eg TextView and Button in inside RelativeLayout

  • Gilgw

    I just tried this tutorial with Android Studio 1.1. RC1 but running the application throws me the following error:
    java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
    Any idea why?

  • Shuvo Joseph

    Attempt to invoke virtual method
    ‘void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)’ on a null object reference at
    com.XXX.YYY.ZZZ.NavigationDrawerFragment.onCreate(NavigationDrawerFragment.java:159)
    Which is
    expListView.setAdapter(listAdapter); // line 159
    where expListView is ExpandableListView and listAdapter is ExpandableListAdapter.
    //listAdapter initialize
    listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
    This is written in NavigationDrawerFragment which extends Fragment.

    • Shuvo Joseph

      Solved it. Thanks for the tutorial 🙂

  • mortenslotthansen

    Consider moving inflator instantiation to constructor and then use parent as 2 argument when calling inflate ie.

    convertView = this.infalInflater.inflate(R.layout.list_item, parent, false);