BaseExpandableListAdapter With Example In Android Studio

BaseExpandableListAdapter is a base class for the ExpandableListAdapter which is used to fill the data and Views from some data (i.e. Arraylist, HashMap etc) to an ExpandableListView. For Creating a custom ExpandableListView we need to create a custom class and then extends BaseExpandableListAdapter class in that class.

BaseExpandableListAdapter in Android

An adapter is a bridge between UI component and data source which fill data in UI component. It holds the data and then send the data to Adapter view then view can takes the data from the Adapter view and shows the data on different views like as ExpandableListView or you can say An adapter is that links an ExpandableListView with the underlying data. The implementation of this interface will provide access to the data of the children (categorized by groups), and also instantiate views for the children and groups.

Below is an example code of BaseExpandableListAdapter  in which we create a custom adapter class named “MyAdapter” and then extends BaseExpandableListAdapter in that class.

public class MyAdapter extends BaseExpandableListAdapter {

@Override
public int getGroupCount() {
return 0;
}

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

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

@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}

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

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

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

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

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
return null;
}

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

In above code snippet we see the overrided functions of BaseExpandableListAdapter which are used to set the data in the ExpandabelListView. There are mainly two methods named getChildView() and getGroupView() that are used to create the View corresponding to our layout (i.e. one is for the items (child items) and one for the groups (parent)).

1. getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent): This method is used when we need to create a child View means a child item for a parent or group.

Paramters:

  • groupPosition: This is the first parameter that tells the position for the parent(group) of the current child. The function returns an integer type value.
  • childPosition: This is the second parameter that tells the position for current child item of the parent.
  • isLastChild: This is the third parameter that returns Boolean value. It returns true if the current child item is the last child within its group and false if it’s not.
  • convertView: This is the fourth parameter that returns View which is used to set the layout for child items.
  • Parent: parent is the fifth or last parameter that is used to set the view for the parent or group item.  The eventual parent of this new View.

2. View  getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent): This method is used when we need to create our group or parent View .

Paramters:

  • groupPosition: This is the first parameter that tells the position for the parent or group of the child. The function returns an integer type value.
  • isExpanded: This is the second parameter that returns Boolean value. It returns true if the current group is expanded and false if it’s not.
  • convertView: This is the fourth parameter that returns View which is used to set the layout for group items.
  • Parent: This is the fifth or last parameter that is used to set the view for the parent or group item.  The eventual parent of this new View.

3. getChild(int groupPosition, int childPosition): This method gets the data associated with the given child within the given group.

Parameters:

  • groupPosition: This is the first parameter that tells the position for the parent or group of the child. This function returns an integer type value
  • childPosition: This is the second parameter that tells the position for the child of the given group. This function returns an integer type value.

4. getGroup(int groupPosition): This method gets the data associated with the given group.

Parameters:

  • groupPosition: This is the parameter that tells the position for the parent or group of the child. This function returns an integer type value

5. getChildrenCount(int groupPosition): This function gets the number of children in a specified group.

Parameters:

  • groupPosition: This parameter tells the position for the parent or group of the child and by using that position we calculate the number of children in that group.

6. getGroupCount(): This function is used to get the total number of groups.

7. getGroupId(int groupPosition): This function is used to get the ID for the group at the given position.

Parameters:

  • groupPosition: This parameter tells the position for the parent or group of the child and by using that position we get the ID for the group.

8. getChildId(int groupPosition, int childPosition): This function is used to gets the ID for the given child within the given group.

Parameters:

  • groupPosition: This is the first parameter that tells the position for the parent or group of the child. This function returns an integer type value
  • childPosition: This is the second parameter that tells the position for the child of the given group. This function returns an integer type value and by using  that value we gets the ID for that.

9. hasStableIds: This method Indicates that whether the child and group ID’s are stable across changes to the underlying data.

10. isChildSelectable(int groupPosition, int childPosition): This mehod checks whether the child at the specified position is selectable or not. This method returns an Boolean value means true or false. It returns true if the child is selectable and false if it’s not.

Parameters:

  • groupPosition: This is the first parameter that tells the position for the parent or group of the child. This function returns an integer type value.
  • childPosition: This is the second parameter that tells the position for the child of the given group. This function returns an integer type value and by using that value we checks whether the child is selectable or not.

BaseExpandableListAdapter Example In Android Studio

Below is the example of BaseExpandableListAdapter in Android where we display an ExpandableListView with team name and their players. In this example we display Team names as an group items and their Player names as an child items for a particular group. In this we implement setOnChildClickListener() and setOnGroupClickListener() events and whenever a user clicks on a child or a group item the name of the item (player or team) is displayed by using a Toast.

Download Code ?

BaseExpandableListAdapter Example In Android Studio

Step 1Create a new project and name it BaseExpandableListAdapter

Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:

In this step we open an xml file and add the code for displaying an ExpandableListView by using its different attributes.

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ExpandableListView
        android:id="@+id/simpleExpandableListView"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:divider="#0f0"
        android:dividerHeight="1dp" />

</RelativeLayout>

Step 3: Create a new xml file for group items Open res -> layout-> group_items.xml and add following code:

In this step we add the code for displaying a TextView for team names.

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

    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="35sp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

</LinearLayout>

Step 4: Create a new xml file for group items Open res -> layout ->child_items.xml and add following code :

In this step we add the code for displaying text view for player name.

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

    <TextView
        android:id="@+id/childItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 5: Open   src -> package -> MainActivity.java

In this step we open MainActivity and add the code to  initiate the ExpandableListView and then add the data to lists for displaying in a ExpandableListView using model classes. Finally set the Adapter that fills the data in the ExpandableListView. In this we implement setOnChildClickListener() and setOnGroupClickListener() events and whenever a user clicks on a child or a group item the name of the item is display by using a Toast.

package example.abhiandroid.BaseExpandableListAdapterExample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.LinkedHashMap;

public class MainActivity extends AppCompatActivity {

    private LinkedHashMap<String, GroupInfo> team = new LinkedHashMap<String, GroupInfo>();
    private ArrayList<GroupInfo> deptList = new ArrayList<GroupInfo>();

    private CustomAdapter listAdapter;
    private ExpandableListView simpleExpandableListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // add data for displaying in expandable list view
        loadData();

        //get reference of the ExpandableListView
        simpleExpandableListView = (ExpandableListView) findViewById(R.id.simpleExpandableListView);
        // create the adapter by passing your ArrayList data
        listAdapter = new CustomAdapter(MainActivity.this, deptList);
        // attach the adapter to the expandable list view
        simpleExpandableListView.setAdapter(listAdapter);

        // setOnChildClickListener listener for child row click
        simpleExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                //get the group header
                GroupInfo headerInfo = deptList.get(groupPosition);
                //get the child info
                ChildInfo detailInfo = headerInfo.getPlayerName().get(childPosition);
                //display it or do something with it
                Toast.makeText(getBaseContext(), " Team And Player :: " + headerInfo.getName()
                        + "/" + detailInfo.getName(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
        // setOnGroupClickListener listener for group heading click
        simpleExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                //get the group header
                GroupInfo headerInfo = deptList.get(groupPosition);
                //display it or do something with it
                Toast.makeText(getBaseContext(), " Team Name :: " + headerInfo.getName(),
                        Toast.LENGTH_LONG).show();

                return false;
            }
        });


    }

    // load some initial data into out list
    private void loadData() {

        addProduct("India", "Virat Kohli");
        addProduct("India", "Mahendar Dhoni");
        addProduct("India", "Yuvraj Singh");

        addProduct("Australia", "Brat Lee");
        addProduct("Australia", "Hayden");

    }


    // here we maintain team and player names
    private int addProduct(String teamName, String playerName) {

        int groupPosition = 0;

        //check the hash map if the group already exists
        GroupInfo headerInfo = team.get(teamName);
        //add the group if doesn't exists
        if (headerInfo == null) {
            headerInfo = new GroupInfo();
            headerInfo.setName(teamName);
            team.put(teamName, headerInfo);
            deptList.add(headerInfo);
        }

        // get the children for the group
        ArrayList<ChildInfo> productList = headerInfo.getPlayerName();
        // size of the children list
        int listSize = productList.size();
        // add to the counter
        listSize++;

        // create a new child and add that to the group
        ChildInfo detailInfo = new ChildInfo();
        detailInfo.setName(playerName);
        productList.add(detailInfo);
        headerInfo.setPlayerName(productList);

        // find the group position inside the list
        groupPosition = deptList.indexOf(headerInfo);
        return groupPosition;
    }

}

Step 6: Create a New Class Open -> package – > GroupInfo.Java and add the following code.

In this step we create an class for set and get the group item name and child items info according to a particular group. GroupInfo is an model class used to set the name of the group item and child items information from your MainActivity and then get the information within Adapter class. Finally set the value to ExpandableListView.

package example.abhiandroid.BaseExpandableListAdapterExample;

import java.util.ArrayList;

public class GroupInfo {

    private String teamName;
    private ArrayList<ChildInfo> list = new ArrayList<ChildInfo>();

    public String getName() {
        return teamName;
    }

    public void setName(String teamName) {
        this.teamName = teamName;
    }

    public ArrayList<ChildInfo> getPlayerName() {
        return list;
    }

    public void setPlayerName(ArrayList<ChildInfo> playerName) {
        this.list = playerName;
    }

}

Step 7: Create a New Class Open -> package – > ChildInfo.Java and add the following code.

In this step we create an class for set and get the name for the child item. ChildInfo is an model class used to set the name of the child item from your Mainactivity and then get the name within adapter class. Finally set the value to ExpandableListView.

package example.abhiandroid.BaseExpandableListAdapterExample;

public class ChildInfo {

    private String playerName = "";

    public String getName() {
        return playerName;
    }

    public void setName(String playerName) {
        this.playerName = playerName;
    }

}

Step 8: Create a New Class Open -> package – > CustomAdapter.Java and add the following code.

In this step we create an custom adapter and then extends BaseExpandableListAdapter in that class. Finally set the data in the ExpandableListView from GroupInfo and ChildInfo model classes.

package example.abhiandroid.BaseExpandableListAdapterExample;

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.ArrayList;


/**
 * Created by Gourav on 08-03-2016.
 */
public class CustomAdapter extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<GroupInfo> teamName;

    public CustomAdapter(Context context, ArrayList<GroupInfo> deptList) {
        this.context = context;
        this.teamName = deptList;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList<ChildInfo> productList = teamName.get(groupPosition).getPlayerName();
        return productList.get(childPosition);
    }

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

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View view, ViewGroup parent) {

        ChildInfo detailInfo = (ChildInfo) getChild(groupPosition, childPosition);
        if (view == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = infalInflater.inflate(R.layout.child_items, null);
        }
        TextView childItem = (TextView) view.findViewById(R.id.childItem);
        childItem.setText(detailInfo.getName().trim());

        return view;
    }

    @Override
    public int getChildrenCount(int groupPosition) {

        ArrayList<ChildInfo> productList = teamName.get(groupPosition).getPlayerName();
        return productList.size();

    }

    @Override
    public Object getGroup(int groupPosition) {
        return teamName.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return teamName.size();
    }

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

    @Override
    public View getGroupView(int groupPosition, boolean isLastChild, View view,
                             ViewGroup parent) {

        GroupInfo headerInfo = (GroupInfo) getGroup(groupPosition);
        if (view == null) {
            LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inf.inflate(R.layout.group_items, null);
        }

        TextView heading = (TextView) view.findViewById(R.id.heading);
        heading.setText(headerInfo.getName().trim());

        return view;
    }

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

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

}

Output:

Now run the App and you will see Team and player names displayed in ExpandableListView. This we have done using BaseExpandableListAdapter in Android.

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

Leave a Reply

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