Skip to main content

Simple Expandable Listview android

Expandable List View:

  In this tutorial you are about to learn how to create an Expandable List view . Before getting into the tutorial we will be using a new datatype in this tutorial. You have to know about it . So here it comes,


HashMap<String,List<String>>  :

Eg:
      Heading="Animals";
     String[] child_animal= { "Lion","Tiger"};
     HashMap<Heading,child_animal>;

It is used to bind the data with the particular parent.

This tells the Java compiler that the child data(Lion,Tiger) have to be placed under the heading named Animals.

So Let's Start

First things , first, we need three layout files.

1 Activity_main.xml:
  
   This is where we are going to declare our Expandable list . which is as follows.
<ExpandableListView   
 android:layout_gravity="start"   
 android:id="@+id/theexpandables"   
 android:layout_width="match_parent"   
 android:layout_height="wrap_content"   
 android:choiceMode="singleChoice"   
 android:childDivider="#7F7F7F"   
 android:dividerHeight="2dip"  
 android:divider="#7F7F7F"  
 android:listSelector="#8BC34A"   
 android:background="#FFFFFF"   
 android:scrollbars="vertical"></ExpandableListView> 

2. Parent_View.xml:
        Here you have to add a Textview. We will invoke this layout in our Adapter class and display the Heading data using this particular text view.


<TextView    
 android:paddingTop="15dp"    
 android:paddingBottom="5dp"  
 android:paddingLeft="50dp"    
 android:paddingRight="30dp"    
 android:layout_width="fill_parent"    
 android:layout_height="50dp"    
 android:background="#3F51B5"    
 android:id="@+id/parenttext"    
 android:textSize="17dp"    
 android:textColor="#FFFFFF"/>  

3. Child_View.xml:

    Here you have to add a Textview. We will invoke this layout in our Adapter class and display the child data using this particular text view.




<TextView    
 android:paddingTop="15dp"    
 android:paddingBottom="5dp"  
 android:paddingLeft="50dp"    
 android:paddingRight="30dp"    
 android:layout_width="fill_parent"    
 android:layout_height="50dp"    
 android:background="#3F51B5"    
 android:id="@+id/parenttext"    
 android:textSize="17dp"    
 android:textColor="#FFFFFF"/>  


4. myExpandableAdapter.java:

public class myExpandableadapter extends BaseExpandableListAdapter  
 {  private Context mcontext;  
   private List<String> parent;  
   private HashMap<String, List<String>> bind_and_display;  
   public myExpandableadapter(Context context, List<String> listDataHeader,  
                 HashMap<String, List<String>> listChildData)  
   {  
   this.mcontext=context;  
     this.parent=listDataHeader;  
     this.bind_and_display=listChildData;  
   }  
   @Override  public int getGroupCount() {  
     return this.parent.size();  
   }  
   @Override  public int getChildrenCount(int groupPosition) {  
     return this.bind_and_display.get(this.parent.get(groupPosition))  
         .size();  
   }  
   @Override  public Object getGroup(int groupPosition) {  
     return this.parent.get(groupPosition);  
   }  
   @Override  public Object getChild(int groupPosition, int childPosition) {  
     return this.bind_and_display.get(this.parent.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 false;  
   }  
   @Override  public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {  
     String parent_text= (String) getGroup(groupPosition);  
    //get the parent data from the particular position passed in the adapter from mainactivity.java  
   LayoutInflater parInflater = (LayoutInflater) this.mcontext      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
   convertView = parInflater.inflate(R.layout.parent_view, null);  
     TextView textparent = (TextView) convertView.findViewById(R.id.parenttext);  
     textparent.setText(parent_text);  
     // Assign the heading to the textview in the parent layout.    
     return convertView;  
   }  
   @Override  public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {  
     String child_text=(String ) getChild(groupPosition, childPosition);  
     //get the data from the current child position   
       LayoutInflater infalInflater = (LayoutInflater) this.mcontext          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
       convertView = infalInflater.inflate(R.layout.child_view, null);  
     TextView textchild = (TextView) convertView.findViewById(R.id.childtext);  
     textchild.setText(child_text);  
    //set the retrieved data to the textview in the child layout.   
     return convertView;  
   }  
   @Override  public boolean isChildSelectable(int groupPosition, int childPosition) {  
     return true;  
   }  
 }  

5.String.xml:

<string-array name="Parent_head">  
   <item>Animals</item>  
   <item>Birds</item>  
   </string-array>  
   <string-array name="Child_animals">  
   <item>Lion</item>  
   <item>Tiger</item>  
   </string-array>  
 <string-array name="child_birds">  
   <item>Parrot</item>  
   <item>Dove</item>  
  </string-array>  

6. MainActivity.Java:



public class MainActivity extends Activity implements ExpandableListView.OnChildClickListener {  
   public myExpandableadapter adapter;  
   public ExpandableListView myexpandable;  
   public List<String> parent;  
   public List<String> child;  
   HashMap<String,List<String>> bind_and_display;  
   @Override  protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     myexpandable=(ExpandableListView) findViewById(R.id.theexpandables);  
     bind_and_display=new HashMap<String,List<String>>();  
     parent = new ArrayList<String>();  
     child=new ArrayList<String>();  
     parent= Arrays.asList(getResources().getStringArray(R.array.Parent_head));  
 //Adding string array element to the parent list      
 // you can also add item one by one like the following      
 //parent.add("Animals")      
 //parent.add("Birds")  
    bind_and_display.put(parent.get(0),Arrays.asList  
    (getResources().getStringArray(R.array.Child_animals)));  
 // Here we bind child list data under the particular heading      
  // you can also bind data like this      
 //List<String> anim= new ArrayList<String>();      
 // anim.add("Lion");      
 //anim.add("Tiger");      
 // bind_and_display(Parent.get(0),anim);      
 //so what happened now is "lion, tiger" is placed under heading "Animals"  
     bind_and_display.put(parent.get(1),Arrays.asList(getResources().getStringArray(R.array.child_birds)));  
  adapter = new myExpandableadapter(this, parent, bind_and_display);  
 // passing our current application context , parent data,  
  and child data to the custom adapter class  
    myexpandable.setAdapter(adapter);  
     //setting the Expandable listview with our custom adapter, which populates the data inside the Expandable Listview.  
    myexpandable.setOnChildClickListener(this);  
 //your class should implemet ExpandableListView.OnChildClickListener  
   }  
   @Override  public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.menu_main, menu);  
     return true;  
   }  
   @Override  public boolean onOptionsItemSelected(MenuItem item) {  
     int id = item.getItemId();  
     if (id == R.id.action_settings) {  
       return true;  
     }  
     return super.onOptionsItemSelected(item);  
   }  
   @Override    
  //this is where we will handle which item is pressed    
  public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {  
     int gposition=groupPosition;  
     int cposition=childPosition;  
     Displayitemclicked(gposition,cposition);  
 //passing the integer value of grouposition and childposition to the above method when an   
 item is clicked  
     return false;  
   }  
   private void Displayitemclicked(int gposition, int cposition) {  
 //Display a message with which item is clicked.      
    if(gposition==0)  
     {  
       switch (cposition)  
       {  
         case 0:  
           Toast.makeText(this,"Lion",Toast.LENGTH_SHORT).show();  
           break;  
         case 1:  
           Toast.makeText(this,"Tiger",Toast.LENGTH_SHORT).show();  
           break;  
       }  
     }  
     else if(gposition==1)  
     {  
       switch (cposition)  
       {  
         case 0:  
           Toast.makeText(this,"Parrot",Toast.LENGTH_SHORT).show();  
           break;  
         case 1:  
           Toast.makeText(this,"Dove",Toast.LENGTH_SHORT).show();  
           break;  
       }  
     }  
   }  
 }  

That's it  our expandable list view is done.

You can download the complete Android Studio project from here Download link











                 

Comments

Popular posts from this blog

Hiding a Child item(ImageView) In ListView

Download Complete Android Studio Project by  Clicking Here . Important Things About Listview: i.                A List view Recycle it’s view. Meaning If your screen can only fit 5 items. But the total number of item   you are about to display in listview is 100 . ii.               Android won’t load these 100 items into the listview when you set your adapter. iii.             Instead it first load the first five Items on the screen and when you scroll down , it fills the new data into the listview, Which improves performance and Memory. ListView at First Load Item 1   Item 2 Item 3 Item 4 Item 5 ListView When Scrolled Item 3   Item 4 Item 5 Item 6 ...

Adding Json array to Serializable Class using Gson.

Why you should use Gson and Serializable Class to Handle Json Data: Gson can be used along with Serializable class to save variables, unnecessary loops and memory  to save the data you get from Json.  Let's Imagine you have array of contact detail and its total count is four. which is something like this. Json Snippet: [ { "name" : "Mark" , "phoneNumber" : "1008788666" , "emailId" : "mark@mail.com" , "address" : "600 Pennsylvania Avenue, Washington DC" }, { "name" : "Christian" , "phoneNumber" : "8007780066" , "emailId" : "christian@mail.com" , "address" : "11 Wall Street New York" }, { "name" : "Benedict" , "phoneNumber" : "4258781555" , "emailId" : "ben...

Sugar ORM With Sqlite Android Part I

Sugar ORM  Android Part I:              If you have came this far in search of how to use an ORM database with your application , you are very much familiar with pain that SQLite querying concept is giving you for all basic CRUD operations with the database. Sugar ORM is  one of the solution which is available for you to carry out CRUD operation in ease, There is no need to use cursor  for reading from database, Sugar ORM speaks Object with Sqlite database. Sugar ORM consider a row of data as Object, where SQLite consider it as record. In this example I am going to show you how to create a table and add data to it using Sugar ORM. Let's get started. 1. Library Inclusion First and Foremost thing, add Sugar ORM to your project by adding the following line to your app dependencies. compile 'com.github.satyan:sugar:1.4' 2. Add Database configuration to Application Manifest: We have to inform the android sdk, that...