Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.

By | April 10, 2011

Hi all……

Here is a simple example of expandandable ListView in ANDROID.
But I am not going to explain any code, because everything is explained inside the java file.
Make sure to read it.

Expandable ListView

package pack.Coderzheaven;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;

public class ExpandableListDemo extends ExpandableListActivity {

	@SuppressWarnings("unchecked")
	public void onCreate(Bundle savedInstanceState) {
    	try{
    		 super.onCreate(savedInstanceState);
    		 setContentView(R.layout.main);

        SimpleExpandableListAdapter expListAdapter =
			new SimpleExpandableListAdapter(
					this,
					createGroupList(), 				// Creating group List.
					R.layout.group_row,				// Group item layout XML.
					new String[] { "Group Item" },	// the key of group item.
					new int[] { R.id.row_name },	// ID of each group item.-Data under the key goes into this TextView.
					createChildList(),				// childData describes second-level entries.
					R.layout.child_row,				// Layout for sub-level entries(second level).
					new String[] {"Sub Item"},		// Keys in childData maps to display.
					new int[] { R.id.grp_child}		// Data under the keys above go into these TextViews.
				);
			setListAdapter( expListAdapter );		// setting the adapter in the list.

    	}catch(Exception e){
    		System.out.println("Errrr +++ " + e.getMessage());
    	}
    }

	/* Creating the Hashmap for the row */
	@SuppressWarnings("unchecked")
	private List createGroupList() {
	  	  ArrayList result = new ArrayList();
	  	  for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
	  		HashMap m = new HashMap();
	  	    m.put( "Group Item","Group Item " + i ); // the key and it's value.
	  		result.add( m );
	  	  }
	  	  return (List)result;
    }

	/* creatin the HashMap for the children */
    @SuppressWarnings("unchecked")
	private List createChildList() {

    	ArrayList result = new ArrayList();
    	for( int i = 0 ; i < 15 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
    	  /* each group need each HashMap-Here for each group we have 3 subgroups */
    	  ArrayList secList = new ArrayList();
    	  for( int n = 0 ; n < 3 ; n++ ) {
    	    HashMap child = new HashMap();
    		child.put( "Sub Item", "Sub Item " + n );
    		secList.add( child );
    	  }
    	 result.add( secList );
    	}
    	return result;
    }
    public void  onContentChanged  () {
    	System.out.println("onContentChanged");
	    super.onContentChanged();
    }
    /* This function is called on each child click */
    public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
    	System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
    	return true;
    }

    /* This function is called on expansion of the group */
    public void  onGroupExpand  (int groupPosition) {
    	try{
    		 System.out.println("Group exapanding Listener => groupPosition = " + groupPosition);
    	}catch(Exception e){
    		System.out.println(" groupPosition Errrr +++ " + e.getMessage());
    	}
    }
}

The main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <ExpandableListView android:id="@+id/android:list"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:background="@drawable/bkg"/>

     <TextView android:id="@+id/android:empty"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:text="No items"/>
</LinearLayout>

The child_row.xml

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

    <TextView android:id="@+id/grp_child"
         android:paddingLeft="50px"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="normal"
         android:layout_width="150px"
         android:layout_height="wrap_content"/>

</LinearLayout>

The group_row.xml

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

    <TextView android:id="@+id/row_name"
         android:paddingLeft="50px"
         android:textSize="20px"
         android:textColor="@drawable/blue"
         android:textStyle="normal"
         android:layout_width="320px"
         android:layout_height="wrap_content"/>

</LinearLayout>

The strings.xml (This file contains the string for the color that is used for text in the ListView)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExpandableList Demo</string>
    <drawable name="white">#ffffff</drawable>
	<drawable name="blue">#2554C7</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="orange">#ff9900</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="gray">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
</resources>

The manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.ExpandableListtwo"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ExpandableListDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Please leave your comments if the post was useful.
Follow me on facebook, twitter and google plus for more updates.

Download.

111 thoughts on “Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.

    1. James Post author

      Haresh we have send you the code.. If you didn’t get it, please leave a comment here.

      Reply
  1. James Post author

    Hello Haresh…..
    You can just make new project and copy and paste the code into their respective files.
    I have given the file names to copy on top of each code also.
    Additionally you need only an image named “bkg.png” or “bkg.jpg” in your drawable folder. that’s all……..
    If Still you couldn’t get it. Kindly leave a comment. We are here to help you.

    Reply
  2. JS

    Great tutorial! I ‘m interested in making a n level tree any suggestions on how to do that?
    Thanks

    Reply
    1. James Post author

      Hi JS….
      I think you can return another expandable Listview to create an n level tree in the following function by extending BaseExpandableListAdapter class..

      public View getGroupView(int groupPosition, boolean isExpanded,
      View convertView, ViewGroup parent)

      Reply
  3. rajesh

    hi,
    you created single row listview…for that you created the chaild list view…….but my problem is i want to make main listview with two rows…..how can i plz????

    Reply
    1. James Post author

      @rajesh : i have explained this in one of the comments above (in reply to JS). Currently I am little busy in my company project. So I can’t produce a sample for you now.

      Reply
  4. chandu

    hi!
    i need a two row(two rows text in group list) expandable list view if psbl pls help me…….

    Reply
  5. Aagrah

    Hii Haresh,
    Is there any way to customize the parent row of the list, I mean the row which is opening the child row(Group Item 1)?

    Reply
    1. James Post author

      if you want to customize group, then change the color or something in group_row.xml

      Reply
  6. John

    Which API are you compiling against? I tried this with two emulator instances, one running Android 2.2 and the other with the Google APIs for 2.2 (both level 8). When loaded, all I get is a blank screen 🙁

    Reply
    1. James Post author

      It will work with all API’s. I was using ANDROID 2.0 when I wrote it. Check the Logcat if you got any errors or not. Check whether you have copied everything perfectly. Drag and copy the code, don’t double click and copy.

      Reply
  7. wang_peng1

    can yousend me your code or give me a link about the download it

    Reply
    1. James Post author

      Hello wang_peng1, We have sent you the code. Please check your mail and leave us a comment.

      Reply
  8. ishan

    icant make it correnctly. igot an error
    can u please send me the code please >>

    Reply
  9. ishan

    thankz u very much..i got the project.and it works .u seems to be very help full. i have lot of problems with android..how can i ask .. post a comment or somethig else .please tell me.. 😀

    Reply
    1. James Post author

      Hi ishan,
      Post your doubts as comments….If we have time we will solve your problem for sure…..

      Reply
  10. Joint pain relief

    I just signed up to your blogs rss feed. Will you post more on this subject?

    Reply
  11. Padmanbhan

    Can we get dynamic data from database when we click the Group item.

    Reply
    1. James Post author

      @padmanabhan : You can do whatever you like on group item click. There is a listener for group item in the program please check.

      Reply
  12. july

    hi, please send me the complete code .
    Thanks in advance.

    Reply
    1. James Post author

      July – Please check your mail, we have mailed you the code.

      Reply
  13. Anna

    hi, please send me the complete code .
    Thanks in advance

    anna

    Reply
    1. James Post author

      Hello Anna,
      Please check your mail we have send you the whole project.

      Reply
  14. Jitendra

    Can we fix the parent in expandable listview. Please give me any suggestion if we can’t.

    Reply
    1. James Post author

      What are you trying to say? Can you please explain.

      Reply
      1. Jitendra

        When we scroll the expandable list view then parent also scroll with child. I want to fix parent when we scroll child.

        Reply
  15. Neha

    Hi,

    Can you tell me how to drag the child items in list2, if we have xml which is divided into 2 lists, list1 & list2.We are displaying expandable list in list1 & want to drag the child items in list2.

    Please tell me if u know.

    Regards,
    Neha

    Reply
    1. James Post author

      Hello Praveen:- Please check your mail. We have sent you the code.

      Reply
  16. Gabriela

    Hello,
    Is the code public? If so, can you please send me the source code? Thx either way, have a nice day.

    Reply
  17. sujs

    Hi James,
    Can you please send me the code. How to get dynamic data onclick of group item, can u please give an hint.

    Thank you.

    Reply
  18. Roman

    Hello

    thank you for this example. I am currently trying to use the ExpandableListView in an Activity which does not extends ExpandableListActivity. I want to create a Layout which is divided in two LinearLayouts. The inner one holds some textViews and images. And the outer one holds the ExpandableListView.

    The application has one “StartActivity” but even before i open the Activity with the ExpandableListView the application crashes.

    Do you have some simple code or tutorial for this? Would be great. Thanks in advance.

    Reply
    1. James Post author

      Hello Roman :- Check your inbox. we have send you the code for Expandable Lists.

      Reply
  19. Kfir

    Hi,

    I’m also like to user an ExpandableListView in an Activity which is not ExpandableListActivity. I’m trying to create a layout which have expandable list view which act as multiple options list right beside regular button which suppose to start a test.
    How can I do that?
    Thanks in advanced.

    Reply
    1. James Post author

      You can have an activity which expands ExpandableListActivity and add other views like buttons in that. No Problem.

      Reply
  20. Jyothi

    How to show main items following subitems automatically (without clicking main item) using listview in android? If I use ExpandableListActivity, I need to click on the main item to see the subitems. I want to show mainitem following subitems at one instance(click evnt is not neede.When I run my application, I want both main item and subitems must be displayed on the emulator. how can i achieve this using listview? Please help me.

    Reply
    1. James Post author

      Hello Jyothi.
      The use some custom Layout. you dont need ExpandableList.

      Reply
  21. chris

    Hello,
    Wow this is awesome,
    Can you please send me the full source code? have a nice day.

    How to use ExpandableListActivity to open another activity?
    Please help me.

    Reply
  22. Ivan

    Hi,

    Thanks for the post, could you please send me the source code. I like to try it out

    Reply
  23. Aric Michael Warden

    Exactly what I looking for…thanks
    A little late…but could I get source code too?

    Reply
  24. kent

    this tutorial realy helps my project but i’m having problem putting images in group and child rows… id like to have little thumbnails beside the button.. can you please send me some samples?? and i samples that group and child are manualy made.. i cant edit it since it’s looped.. thanks in advance. please reply.. my deadline is friday

    Reply
  25. Dc

    Tyvm for the useful posts,
    however it is not working on my computer, it suns fine and it says it was successful but i dont see screen like yours, all i see is my bkg pic, any idea?
    thx in advance

    Reply
  26. rizaozdulger

    Hi,

    Thanks to the post.

    Can you send me the code please?

    Thanks again!

    Reply
  27. Seshu

    Hi. Good tutorial.. can u send the code to my mail. this is my mail id s.seshu143attherate gmaildotcom.. thank Q.

    Reply
  28. Kaushal

    Hi,

    This is really good tutorial and very helpful.

    Can anyone have an idea to hide the default expand/collapse icon?

    Thanks in advance,

    Reply
  29. Mufaddal

    Hi,

    How do we make multicolumn expandablelistview.

    I added the things to the hashmap and also to the XML but no luck like the way it is described for ListView.

    TY

    Reply
    1. James Post author

      What do you mean by multicolumn? You can have any custom layout for the row.

      Reply
    2. Thomas

      I think I know what you’re trying to do. I couldn’t find any documentation on doing this either, but I just kept trying different things and figured this out. My code is based on the code on this page so you should be able to figure it out.

      First the java code:

      //for each slqite column this create 4 subrow columns where my database column names are Item, QuantitySold, SoldPrice and SetPrice. This is done right before returning the child list.

      for( int n = 0 ; n < mycursor.getCount(); n++ ) {

      HashMap child = new HashMap();

      child.put( "Sub Item", mycursor.getString(mycursor.getColumnIndex("Item")) );

      child.put( "Sub Item1", mycursor.getString(mycursor.getColumnIndex("QuantitySold")) );

      child.put( "Sub Item2", mycursor.getString(mycursor.getColumnIndex("SoldPrice")) );

      child.put( "Sub Item3", mycursor.getString(mycursor.getColumnIndex("SetPrice")) );
      secList.add( child );
      mycursor.moveToNext();
      }
      result.add( secList );
      }
      }
      return result;
      ———————-
      And here is my adapter formatting:

      mAdapter = new SimpleExpandableListAdapter(this, createGroupList(),R .layout.expandable_list_item1,new String[] { "Group Item" }, new int[] { R.id.toprow_name }, createChildList(), R.layout.expandable_list_item2, new String[] {"Sub Item", "Sub Item1", "Sub Item2", "Sub Item3"}, new int[] { R.id.subrow_item, R.id.subrow_quantitysold, R.id.subrow_minprice, R.id.subrow_setprice});

      ———————-
      Second my xml layout code (this is crap formatting, its 2:50am and I just figured this out so I havn't written in proper xml format).

      That should do it!

      Reply
      1. Thomas

        Oops, the website grabbed my xml code. I’ll try pasting it again, but basically its just 4 textviews with the id’s I mentioned above (subrow_item, subrow_quantitysold…) with a linear layout that is set to horizontal. I specify the textview width=20dp, but height is set to wrap_content.

        Reply
  30. Andik

    Hi… nice tutorial…
    I’ve searched so many tutorials and examples about usability of expandablelistview, but I think this is the most obvious I’ve ever read…
    May I have the code please… can you send me the complete code via my email: top_x_classix@yahoo.com

    Thanks…

    Reply
  31. Umesh

    Thanks for the very nice tutorial.
    Your code is so simple to understand.
    great job…keep it up

    Reply
  32. Carlos

    Hi, the tutorial is great, I got a fight of two days with tutorials lists and more lists. Now I have a couple of questions that I’m fighting with your code.
    I can not find how to change the bottom of each row according to a condition such as: if (a == 2) row.setBackgroundDrawable (R.drawable.team) elserow.setBackgroundDrawable (R.drawable.only).
    The other is that I need to put the first subitem is fixed, ie
    ITEM TITLE
    Item description: blabla n No. tests n Rating: bla bla
    item team1
    item team2

    the explanation is that I have the title of the race that is first rate, once deployed
    I have the description of the race so many items and then another level as teams.

    Sorry for the long text Thanks

    Reply
  33. vicky

    hey..I’ve downloaded the project…but i got error s on the expandablelist.java…do i need to change anything or add anything to the code to make it working?

    Thanks

    Reply
  34. Saumya

    Hi… Am retrieving data as string from data base to android like name ,address, phone. This is dynamic pull from database i want it to display on android in a list but the activity should not extend ListAcitvity as I do have edit text on same screen. I want to display the name on list and when clicked rest of the details should come , am not able to display the list pls do help me .

    Reply
    1. James Post author

      You can simply change the ListActivity and change the way ListView is referenced. If it is a ListActivity the ListView in the xml has the id = “@android:list” or something. You can simply change this to give ur id and change the way adapter is setup. thats all.

      Reply
  35. mafia wars

    I’ll right away snatch your rss as I can not to find your email subscription hyperlink or newsletter service. Do you have any? Please allow me recognise in order that I may subscribe. Thanks.

    Reply
  36. playfred

    Helpful information. Fortunate me I found your web site by chance, and I’m stunned why this coincidence did not happened in advance! I bookmarked it.

    Reply
  37. Greg

    Great tutorial, thanks! Most tutorials always leave out something critical like the XML file.

    Reply
  38. meena

    hi………..
    This is very helpful for me. because i am new in android development. i am developing Android Digital menu system application.i want one help.
    how to put icons in front of the expanablelist view and how to view the list items like image format…….. please give the sample program…….
    Advance Thanks for our responce……

    Reply
    1. James Post author

      Did you download the sample project I provided below the post, there you can change the adapter for the list.

      Reply
  39. linhlt

    I want to create a multi level list view. I just want to do a simple example about this. Just two class, one class extends Activity, one class extends BaseExpandableListAdapter. I want to know how to implement the class extends BaseExpandableListAdapter to return an expandable list view for multilevel

    Reply
  40. Pingback: ListView with Sections in android. | Coderz Heaven

  41. Nash

    Hi , Can you send me the code for the simple expandablelistview..thanks!

    Reply
    1. James Post author

      The source code is below the post. PLease check that.

      Reply
  42. Pingback: ClassCastException: java.util.HashMap with android SimpleExpandableListAdapter | Software development support, software risk,bugs for bugs, risk analysis,

    1. admin

      hello jayesh patel :- You can download the project from the download link below.

      Reply
  43. Rachelle

    Awesome tutorial thanks!! anyone who uses this don’t forget to put the colours in the string.xml file (I’m not the best at reading and that cost me a lot of unnecessary debugging) 🙂

    Reply
  44. Shrey

    I found it very useful but only thing i found problem was with getting values at the position where i am clicking..

    Reply
  45. Steve

    This has been a great help. The only thing I’m not seeing is how the adapter gets linked to the list view with the name you gave it.

    Reply
  46. krishnaveni

    Hi the above tutorial is very helpful for me..thanks for giving this nice tutorial…but i have one doubts… how is creating 2 groups in this example for separate details.For eg:
    Group name:
    OrderInfo,CustomerInfo.
    Childname(OrderInfo): payment_method
    Childname(CustomerInfo): name,email.
    How is to do.

    Reply
  47. krishnaveni

    Hi i have to created different groups in this example.but i can’t develop different child list is placed in different formats.please refer my code and give me solutions.now i have to created 2 groups in my code.
    I need to place “payment_method” and “total” inside first group,and firstname and lastname is place in second group
    (e.g:Groupname:OrderInfo,customerInfo,
    Childname(OrderInfo):payment_method,total,
    Childname(CustomerInfo):firstname,lastname).
    My code can placed Childname(OrderInfo) inside OrderInfo group, but i wish to need if i have to click customerInfo group means the firstname,lastname also displayed customerInfo group.

    Here first child value is placed first group is successfully finished…but i can’t do place the second child value is placed second group.please help me.how is to do.
    The code is here:http://pastie.org/4520473

    Reply
    1. James Post author

      The full android project is below the post for download.

      Reply
  48. Pingback: android expanlistview arrow : Android Community - For Application Development

  49. Pingback: android expandlistview arrow : Android Community - For Application Development

  50. Pingback: ClassCastException: java.util.HashMap with android SimpleExpandableListAdapter - Tutorial Guruji

Leave a Reply

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