Thursday 18 October 2012

How to use Expandable List in Android

Expandavle list provides a View like this.
It is composed of Group Header and Child Elements.
When arrow is clicked along with the Group header, the list gets expanded and the child elements are shown. Further events could be reaised on the child elements to open another activity or to perform some function.











Step 1: Create the main.xml

create the main.xml in the layout folder and define the Expandable list in the main file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ExpandableListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ExpandableListView>
</LinearLayout>

 Step2: Create thegroup_row.xml

<?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"
    android:background="@android:color/transparent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:orientation="vertical" >
<TextView
   android:id="@+id/tvGroupName"
   android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:textSize="16sp"
    android:textStyle="bold"
android:layout_gravity="center_vertical"
    android:paddingLeft="30dp"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>

Step 3: Create the child_row.xml

<?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"
    android:background="@android:color/transparent"
    android:orientation="vertical" >
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
<TextView
    android:id="@+id/tvPlayerName"
    android:paddingLeft="50dp"
    android:layout_width="wrap_content"
    android:layout_height="30dip"
 
    android:gravity="center_vertical">
 
</TextView>  
</LinearLayout>
</LinearLayout>

Step 4: Create ExpAdapter.java file

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpAdapter extends BaseExpandableListAdapter {

static final String arrGroupelements[] =
{
"India", "Australia", "England", "South Africa"
};

static final String arrChildelements[][] =
{
{
"Sachin Tendulkar", "Raina", "Dhoni", "Yuvi"
},
{
"Ponting", "Adam Gilchrist", "Michael Clarke"
},
{
"Andrew Strauss", "kevin Peterson", "Nasser Hussain"
},
{
"Graeme Smith", "AB de villiers", "Jacques Kallis"
}
};
 private Context myContext;
 public ExpAdapter(Context context) {
  myContext = context;
 }
 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return null;
 }

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

 @Override
 public View getChildView(int groupPosition, int childPosition,
   boolean isLastChild, View convertView, ViewGroup parent) {
 
  if (convertView == null) {
   LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   convertView = inflater.inflate(R.layout.child_row, null);
  }
 
  TextView tvPlayerName = (TextView) convertView.findViewById(R.id.tvPlayerName);
  tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);
 
  return convertView;
 }

 @Override
 public int getChildrenCount(int groupPosition) {
  return arrChildelements[groupPosition].length;
 }

 @Override
 public Object getGroup(int groupPosition) {
  return null;
 }

 @Override
 public int getGroupCount() {
  return arrGroupelements.length;
 }

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

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

  if (convertView == null) {
   LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   convertView = inflater.inflate(R.layout.group_row, null);
  }
 
  TextView tvGroupName = (TextView) convertView.findViewById(R.id.tvGroupName);
  tvGroupName.setText(arrGroupelements[groupPosition]);
 
  return convertView;
 }

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

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

Step 5: Create the MainActivity.java file


import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
public class MainActivity extends ExpandableListActivity
{
static final String arrGroupelements[] =
{
"India", "Australia", "England", "South Africa"
};

static final String arrChildelements[][] =
{
{
"Sachin Tendulkar", "Raina", "Dhoni", "Yuvi"
},
{
"Ponting", "Adam Gilchrist", "Michael Clarke"
},
{
"Andrew Strauss", "kevin Peterson", "Nasser Hussain"
},
{
"Graeme Smith", "AB de villiers", "Jacques Kallis"
}
};

DisplayMetrics metrics;
int width;
ExpandableListView expList;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        expList = getExpandableListView();
        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
//        this code for adjusting the group indicator into right side of the view
        expList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));
        expList.setAdapter(new ExpAdapter(this));
        expList.expandGroup(0);
        expList.setOnGroupExpandListener(new OnGroupExpandListener()
        {
        @Override
        public void onGroupExpand(int groupPosition)
        {
        Log.d("onGroupExpand", "OK");
        }
        });
 
        expList.setOnGroupCollapseListener(new OnGroupCollapseListener()
        {
        @Override
        public void onGroupCollapse(int groupPosition)
        {
        Log.d("onGroupCollapse", "OK");
        }
        });
 
        expList.setOnChildClickListener(new OnChildClickListener()
        {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
        int groupPosition, int childPosition, long id)
        {
        Toast.makeText(getApplicationContext(), "" +  childPosition , Toast.LENGTH_LONG).show();
        Log.d("OnChildClickListener", "OK");
        return false;
        }
        });
}
 
public int GetDipsFromPixel(float pixels)
    {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
    }
}

Now the expandable list is created. Deploy this application on a device with Versions higher than 2.2
Regards:
Sahil Mahajan Mj 

No comments:

Post a Comment