Android Expandable ListView Example Tutorial

Android Expandable ListView Example Tutorial

In this android snippet tutorial, we are going to learn how to create Android ExpandableListView. We have created different tutorials that focused on ListView. If you are interested in other ListView tutorial, you can access them here.

According to Android developers guide – “A view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children. The items come from the ExpandableListAdapter associated with this view.”

Note: You cannot use the value wrap_content for the android:layout_height attribute of a ExpandableListView in XML if the parent’s size is also not strictly specified (for example, if the parent were ScrollView you could not specify wrap_content since it also can be any length. However, you can use wrap_content if the ExpandableListView parent has a specific size, such as 100 pixels.

Now that we have an understanding of what Expandable ListView used for in android, we are going to create Expandable ListView that contains two ListView. Each ListView will serve as a container group to house its own children. When it receives a click, it will expand if it is in collapsed state and likewise.

We are going to create two layouts – one for the Expandable ListView header and the other for its children.

Our activity_main.xml file will contain an Expandable ListView as it serves as the main interface for our application.

Before we start, the first thing I will do is to list the environment and tools I used in this android code snippet but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: ExpandableListViewInAndroid

Package: com.inducesmile.expandablelistviewinandroid

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

Main Layout

We will start by adding an Expandable ListView in our activity_main.xml layout file. If you are using Eclispe or Android Studio, you can switch to the design view and drag and drop Expandable ListView inside your layout file.

You can also copy and paste the following code below into the file if you don’t want to do it yourself.

<RelativeLayout 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"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ExpandableListView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/expandableListView"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:divider="#A4C739"

android:textColor="#000000"

android:dividerHeight="0.5dp"

android:layout_marginTop="20dp" />

</RelativeLayout>

Now we are going to create two different layouts for the Expandable ListView parent header and its children. This will be a simple layout that contain a TextView in it. Copy and paste the code for the two layouts below.

child_layout.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">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:layout_marginTop="20dp"

android:layout_marginLeft="20dp"

android:textSize="16sp"

android:textColor="#000000"

android:id="@+id/child_layout" />

</LinearLayout>

 parent_layout.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">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:layout_marginTop="20dp"

android:layout_marginLeft="20dp"

android:textColor="#000000"

android:textSize="20sp"

android:id="@+id/parent_layout" />

</LinearLayout>

We are going to create a custom adapter which we will use to bind data to the ExpandableListView items. The adapter class inherits from the BaseExpandableListAdapter which has many methods to help to bind data source to items.

The getGroupView is used to inflate the parent_layout we have created to hold the title of each group of items in the ExpandableListView.

package inducesmile.com.expandablelistviewinandroid;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;

public class ExpandableListViewAdapter extends BaseExpandableListAdapter {

private Context context;

private List<String> parentDataSource;

private HashMap<String, List<String>> childDataSource;

public ExpandableListViewAdapter(Context context, List<String> childParent, HashMap<String, List<String>> child) {

this.context = context;

this.parentDataSource = childParent;

this.childDataSource = child;

}

@Override

public int getGroupCount() {

return this.parentDataSource.size();

}

@Override

public int getChildrenCount(int groupPosition) {

return this.childDataSource.get(this.parentDataSource.get(groupPosition)).size();

}

@Override

public Object getGroup(int groupPosition) {

return parentDataSource.get(groupPosition);

}

@Override

public Object getChild(int groupPosition, int childPosition) {

return this.childDataSource.get(parentDataSource.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) {

View view = convertView;

if(view == null){

LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

view = inflater.inflate(R.layout.parent_layout, parent, false);

}

String parentHeader = (String)getGroup(groupPosition);

TextView parentItem = (TextView)view.findViewById(R.id.parent_layout);

parentItem.setText(parentHeader);

return view;

}

@Override

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

View view = convertView;

if(view == null){

LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

view = inflater.inflate(R.layout.child_layout, parent, false);

}

String childName = (String)getChild(groupPosition, childPosition);

TextView childItem = (TextView)view.findViewById(R.id.child_layout);

childItem.setText(childName);

return view;

}

@Override

public boolean isChildSelectable(int groupPosition, int childPosition) {

return true;

}

}

 MainActivity.java

In the MainActivity.java file, we will get the instance of our ExpandableListView, thereafter we will create an object of our adapter and pass the needed data that will bind to the ExpandableListView items. Copy and paste the code below in this file.

package inducesmile.com.expandablelistviewinandroid;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.ExpandableListView;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class MainActivity extends ActionBarActivity {

private ExpandableListView expandableListView;

private List<String>parentHeaderInformation;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

parentHeaderInformation = new ArrayList<String>();

parentHeaderInformation.add("Cars");

parentHeaderInformation.add("Houses");

parentHeaderInformation.add("Football Clubs");

HashMap<String, List<String>> allChildItems = returnGroupedChildItems();

expandableListView = (ExpandableListView)findViewById(R.id.expandableListView);

ExpandableListViewAdapter expandableListViewAdapter = new ExpandableListViewAdapter(getApplicationContext(), parentHeaderInformation, allChildItems);

expandableListView.setAdapter(expandableListViewAdapter);

}

private HashMap<String, List<String>> returnGroupedChildItems(){

HashMap<String, List<String>> childContent = new HashMap<String, List<String>>();

List<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Toyota");

cars.add("Nissan");

List<String> houses = new ArrayList<String>();

houses.add("Duplex");

houses.add("Twin Duplex");

houses.add("Bungalow");

houses.add("Two Storey");

List<String> footballClubs = new ArrayList<String>();

footballClubs.add("Liverpool");

footballClubs.add("Arsenal");

footballClubs.add("Stoke City");

footballClubs.add("West Ham");

childContent.put(parentHeaderInformation.get(0), cars);

childContent.put(parentHeaderInformation.get(1), cars);

childContent.put(parentHeaderInformation.get(2), cars);

return childContent;

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;
}
return super.onOptionsItemSelected(item);
}
}

Save the file and run your project. If everything works for you, an image like this will appear on your test device.

Android Expandable ListView Example Tutorial

Android Expandable ListView Example Tutorial

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

OTHER INTERESTING POSTS:

2 Comments

Add a Comment