ExpandableListView With Source Code In Android Studio - RSM Developer

 

Expandable List View

Step 1: Create a new project and name it Expandable List View.

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 a Expandable List View by using its different attributes.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff"
tools:context=".MainActivity">

<ExpandableListView
android:id="@+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:childDivider="#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 subject 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:background="@color/white"
android:orientation="vertical">

<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="35sp"
android:textColor="#000000"
android:justificationMode="inter_word"
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 two TextView i.e. one for sequence of topics and another for topic 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:textColor="#FFFFFF"
android:orientation="vertical">

<TextView
android:id="@+id/sequence"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingLeft="35sp"
android:textColor="#000000"
android:justificationMode="none"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/childItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/sequence"
android:textColor="#000000"
android:justificationMode="none"
android:textAppearance="?android:attr/textAppearanceMedium" />


</RelativeLayout>

Step 5: Open   Java -> package -> MainActivity.Java

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

package com.bpstudio.expandablelistviewexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

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> subjects = new LinkedHashMap<String, GroupInfo>();
private ArrayList<GroupInfo> deptList = new ArrayList<GroupInfo>();

private CustomAdapter listAdapter;
private ExpandableListView simpleExpandableListView;

@Override
protected 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);

//expand all the Groups
expandAll();

// 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.getProductList().get(childPosition);
//display it or do something with it
Toast.makeText(getBaseContext(), " Clicked on :: " + 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(), " Header is :: " + headerInfo.getName(),
Toast.LENGTH_LONG).show();

return false;
}
});


}

//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.expandGroup(i);
}
}

//method to collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.collapseGroup(i);
}
}

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

addProduct("Mujib Centenary","Bangabandhu Sheikh Mujibur Rahman.");
addProduct("মুজিব শতবর্ষ"," জাতির পিতা বঙ্গবন্ধু শেখ মুজিবুর রহমান ১৯২০ সালের ১৭ মার্চ বাংলাদেশের গোপালগঞ্জ জেলার টুঙ্গিপান গ্রামে জন্মগ্রহণ করেন।");


addProduct("Our National Flag","Our national flag is the symbol of our sovereignty and freedom.");
addProduct("আমাদের জাতীয় পতাকা","আমাদের জাতীয় পতাকা আমাদের সার্বভৌমত্ব ও স্বাধীনতার প্রতীক। আমাদের জাতীয় পতাকা আমাদের জাতীয় জীবনের সবচেয়ে বড় অর্জন।");


addProduct("Climate Change","Climate change is the most important issue in the present world. The causes of climate change can be divided into two categories.");
addProduct("জলবায়ু পরিবর্তন","বর্তমান বিশ্বে জলবায়ু পরিবর্তন একটি অন্যতম গুরুত্বপূর্ণ বিষয়। জলবায়ু পরিবর্তন এর কারণসমূহকে দুটি ক্যাটাগরিতে বিভক্ত করা যেহে পারে। এগুলো হলো, প্রাকৃতিক কারণ এবং মানবসৃষ্ট কারণ।");

}



//here we maintain our products in various departments
private int addProduct(String department, String product){

int groupPosition = 0;

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

//get the children for the group
ArrayList<ChildInfo> productList = headerInfo.getProductList();
//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.setSequence(String.valueOf(listSize));
detailInfo.setName(product);
productList.add(detailInfo);
headerInfo.setProductList(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 a class for setting and getting the group item name and child items info according to a particular group. GroupInfo is a model class used to set the name of the group item and child items information from your main activity and then get the information within Adapter class. Finally set the value to ExpandableListView.

package com.bpstudio.expandablelistviewexample;

import java.util.ArrayList;

public class GroupInfo {

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

public String getName() {
return name;
}

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

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

public void setProductList(ArrayList<ChildInfo> productList) {
this.list = productList;

}
}

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

In this step, we create a class for setting and getting the name and sequence for the child items. ChildInfo is a model class used to set the name of the child item and the sequence of the child item from your main activity and then get the name and sequence within adapter class. Finally set the value to expandable list view.

package com.bpstudio.expandablelistviewexample;

public class ChildInfo {

private String sequence = "";
private String name = "";

public String getSequence() {
return sequence;
}

public void setSequence(String sequence) {
this.sequence = sequence;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;

}
}

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

In this step, we create a CustomAdapter class and then extends BaseExpandableListAdapter in that class. Finally set the data in the ExpandableListView from GroupInfo and  ChildInfo model class.

package com.bpstudio.expandablelistviewexample;


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 RSM Developer on 02-01-2023.
*/
public class CustomAdapter extends BaseExpandableListAdapter {

private Context context;
private ArrayList<GroupInfo> deptList;

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

@Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<ChildInfo> productList = deptList.get(groupPosition).getProductList();
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 sequence = (TextView) view.findViewById(R.id.sequence);
sequence.setText(detailInfo.getSequence().trim() + ". ");
TextView childItem = (TextView) view.findViewById(R.id.childItem);
childItem.setText(detailInfo.getName().trim());

return view;
}

@Override
public int getChildrenCount(int groupPosition) {

ArrayList<ChildInfo> productList = deptList.get(groupPosition).getProductList();
return productList.size();

}

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

@Override
public int getGroupCount() {
return deptList.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 main topics and sub-topics listed in Expandable List View.


Help Video




Post a Comment

Previous Post Next Post

যোগাযোগ ফর্ম