Tuesday, September 18, 2012

Simple Expandable ListView Android.

We are aware about android most powerful feature ListView. We can handle ListView click event eg. clicking on ListView row, we can start a new activity or what ever we want to do.

But it some how strange to many developer, clicking on ListView row it should expand and show more details in spite of opening a new Activity and we can shrink row of ListView after reading details information. This is feature known as ExpandableListView in android.

ExpandableListView is pre-define widget in android . and much similar to android ListView.So here we go for ExpandableListView Simple Example with source code at the end of this article.
Step 1)  create one project. There is only one class to explain here

 package com.ahmad.expandable;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import android.app.ExpandableListActivity;  
 import android.os.Bundle;  
 import android.widget.ExpandableListAdapter;  
 import android.widget.SimpleExpandableListAdapter;  
  * Demonstrates expandable lists backed by a Simple Map-based adapter  
 public class ExpandableList extends ExpandableListActivity {  
   private static final String NAME = "NAME";  
   private static final String IS_EVEN = "IS_EVEN";  
   private ExpandableListAdapter mAdapter;  
   public void onCreate(Bundle savedInstanceState) {  
     List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();  
     List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();  
     for (int i = 0; i < 20; i++) {  
       Map<String, String> curGroupMap = new HashMap<String, String>();  
       curGroupMap.put(NAME, "Group " + i);  
       curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");  
       List<Map<String, String>> children = new ArrayList<Map<String, String>>();  
       for (int j = 0; j < 15; j++) {  
         Map<String, String> curChildMap = new HashMap<String, String>();  
         curChildMap.put(NAME, "Child " + j);  
         curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd");  
     // Set up our adapter  
     mAdapter = new SimpleExpandableListAdapter(  
         new String[] { NAME, IS_EVEN },  
         new int[] { android.R.id.text1, android.R.id.text2 },  
         new String[] { NAME, IS_EVEN },  
         new int[] { android.R.id.text1, android.R.id.text2 }  

                                                    Screen Shot of example


Step 2)  This is step is simple. Download project. And import it to your work space and play with the code as per requirement 


                                 DOWNLOAD SOURCE CODE 

No comments:

Post a Comment