Base Expandable List Adapter in Android with Example


What is the Base Expandable List Adapter in android?

Base Expandable List Adapter is used in android when we have to display a nested list view. We will understand a nested list view by an example. We have to display the tech stacks along with the programming languages used within it. So we can display the tech stacks in the list view such as Android Development, IOS Development and Web Development. Each tech stack has their set of different programming languages so we can display the list of programming languages when a user clicks on any of the tech stack. In this way we will be able to implement a nested list view. For implementation of nested list view we will be using a Base Expandable List Adapter within our android application.

Implement of Base Expandable List Adapter

In this article We will be creating a simple application in which we will be displaying the list of tech stacks. When a user clicks on any of the tech stacks we will be displaying the programming languages which can be used for that specific tech stack. We will be following a step by step guide to implement a toast message in an android application.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Kotlin.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.kt file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?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"
   tools:context=".MainActivity">

   <!-- creating text view for name on below line-->
   <TextView
      android:id="@+id/idTVTitle"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_margin="10dp"
      android:gravity="center"
      android:padding="4dp"
      android:text="Base Expandable List Adapter"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- creating an expandable list view on below line-->
   <ExpandableListView
      android:id="@+id/idExpandableListView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idTVTitle" />

</RelativeLayout>

Explanation − In the above code we are creating a root layout as our Relative Layout. Inside this relative layout we are creating a simple text view which is used to display the heading of the application. After that we are creating an Expandable List View widget which we will be using to display the list of Tech Stacks along with programming languages within our application.

Step 3 : Creating a new Modal class for TechStackItem

Now we will be creating a new modal class for our Tech Stack Item which will contain two variables one for the tech stack name and an array list variable for the list of programming languages which we have to display within that Tech Stack. For creating this class. Navigate to app>java>your app’s package name>Right click on it>New>Java/Kotlin class and name it as TechStackItem and add below code to it.

package com.example.gptapp data class TechStackItem( // on below line creating a string variable for tech stack/ // creating an array list for programming languages within this to display programming languages. var techStack: String, var programmingLanguages: ArrayList<String> )

Step 4 : Creating a new layout file for Programming Language List Item.

As we will be creating an expandable list view so we have to create an individual item view which we have to display for the list view of our programming languages. For creating that navigate to app>res>layout>Right click on it>New>Layout Resource file and name it as programming_lng_list_item and add below code to it.

<?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"> <!-- on below line creating a text view for displaying a programming language --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:id="@+id/idTVProgrammingLng" android:padding="4dp" android:text="Programming Language Item" android:textColor="#FF000000" android:textSize="15sp" /> </RelativeLayout>

Explanation : In the above code we are creating a simple text view which we will be using to display the item within our programming languages list view.

Step 5 : Creating a new layout file for Tech Stack List Item

As we are displaying the list of programming languages when clicking on Tech Stack. For displaying the tech Stack we will have to create a separate layout file for it. For creating a new layout file. Navigate to app>res>layout>Right click on it>New>Layout Resource file and name it as tech_stack_list_item and add below code to it.

<?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="40dp"> <!-- on below line creating a text view for displaying a tech stack --> <TextView android:id="@+id/idTvTechStack" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:gravity="center" android:padding="4dp" android:text="Tech Stack List Item" android:textColor="#FF000000" android:textSize="16sp" android:textStyle="bold" /> </RelativeLayout>

Explanation − In the above code we are simply creating a text view which we will be using to display text for our Tech Stack. We will be using this layout file for the Tech Stack List View.

Step 6 : Creating an adapter class for setting the data to our layout files

Now we have created our layout files for displaying the UI. After that we have to set what data we have to display within our layout files. For setting this data we have to create an adapter class. For creating this adapter class. Navigate to app>java>your app’s package name>Right click on it>New>Java/Kotlin class and name it as CustomListViewAdapter and add below code to it.

package com.example.gptapp import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseExpandableListAdapter import android.widget.TextView // Creating a custom list view adapter on below line. class CustomListViewAdapter( // creating a list for our tech stack on below line and passing tech stack item to it. private val techStackList: List<TechStackItem>, ) : BaseExpandableListAdapter() { // on below line we have to return the size of group in our case is tech stack for programming languages override fun getGroupCount(): Int { return techStackList.size } // below method is use to return size of child list in our case is language list override fun getChildrenCount(groupPosition: Int): Int { val lngList = techStackList.get(groupPosition).programmingLanguages return lngList.size } // on below line we are returning the group from our tech stack list. override fun getGroup(groupPosition: Int): Any { return techStackList.get(groupPosition) } // below method is use to return the item for our child list override fun getChild(groupPosition: Int, childPosition: Int): Any { // on below line we are getting our programming language list from tech stack list val programmingLanguageList = techStackList.get(groupPosition).programmingLanguages // on below line e are getting item from our programming language list which we are taking from tech stack list return programmingLanguageList.get(childPosition) } // below method is use to get group position override fun getGroupId(groupPosition: Int): Long { return groupPosition.toLong() } // below method is use to get child position. override fun getChildId(groupPosition: Int, childPosition: Int): Long { return childPosition.toLong() } // below method is use to return true for stable ids. override fun hasStableIds(): Boolean { return true } // below method is use to inflate layout file for our group items. override fun getGroupView( groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup? ): View { // on below line we are getting our group from tech stack item val techStackItem: TechStackItem = getGroup(groupPosition) as TechStackItem // on below line we are creating a layout inflater variable to inflate our layout file. val inflater = parent!!.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater // on below line we are inflating our layout file for our tech stack item. val view = inflater.inflate(R.layout.tech_stack_list_item, null) as View // on below line we are creating and initializing variable for our tech stack tv. val techStackTV: TextView = view.findViewById(R.id.idTvTechStack) // on below line we are setting text for our tech stack text view. techStackTV.text = techStackItem.techStack // on below line returning the view. return view } // below method is use to inflate layout file for our child view. override fun getChildView( groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup? ): View { // on below line we are getting language from our group val language: String = getChild(groupPosition, childPosition) as String // on below line we are creating a variable for our inflater. val inflater = parent?.context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater // on below line we are inflating a layout file for programming language list item. val view = inflater.inflate(R.layout.programming_lng_list_item, null) as View // on below line we are creating and initializing our text view for programming language. val programmingLngTV: TextView = view.findViewById(R.id.idTVProgrammingLng) // on below line setting data for our text view. programmingLngTV.text = language // on below line returning the view. return view } // below method is use to specify weather the child item will be selectable or not // in our case we are specifying it as selectable. override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean { return true } }

Explanation − In the above code firstly we are expanding our adapter class with BaseExpandableListAdapter and passing our list of data as a parameter within it. Now inside this class we are overriding the methods of BaseExpandableListAdapter class. The method are as follows −

  • getGroupCount() − In this method we have to return the size of the tech stack list which is our parent list.

  • getChildrenCount() − In this method we have to return the size of our programming languages list which is our child list.

  • getGroup() − In this method we have to return the group of tech stack list item which contain a tech stack name and the programming languages present within that tech stack.

  • getChild() − In this method we have to return the programming language item from the programming language list for each tech stack.

  • getGroupId() − In this method we have to simply return the group position.

  • getChildId() − In this method we have to simply return the child position.

  • hasStableIds() − In this method we have to simply return true as we have to display stable ids for our listview items.

  • getGroupView() − In this method we are inflating the layout file for our parent listview which in our case is tech stack so we will be inflating tech_stack_list_item layout.

  • getChildView() − In this method we are inflating the layout file for our child listview which in our case is programming language so we will be inflating programming_lng_list_item layout.

  • isChildSelectable() − In this method we are returning as true as we have to set on click listener for our expandable list view.

Step 7 : Working with MainActivity.kt

Navigate to MainActivity.kt. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.kt to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.gptapp import android.os.Bundle import android.widget.ExpandableListView import android.widget.ExpandableListView.OnChildClickListener import android.widget.ExpandableListView.OnGroupClickListener import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables on below line for array list, adapter and expandable list view. private val techStackList: ArrayList<TechStackItem> = ArrayList() lateinit var customListViewAdapter: CustomListViewAdapter lateinit var expandableLV: ExpandableListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all variables with their ids on below line. expandableLV = findViewById(R.id.idExpandableListView) // on below line initializing our adapter and setting this adapter to expandable list view. customListViewAdapter = CustomListViewAdapter(techStackList) expandableLV.setAdapter(customListViewAdapter) // on below line creating an array list for first tech tack and passing it to our tech stack list with tech stack name val lng1: ArrayList<String> = ArrayList() lng1.add("Java") lng1.add("Kotlin") techStackList.add(TechStackItem("Android Development", lng1)) // on below line creating an array list for second tech tack and passing it to our tech stack list with tech stack name val lng2: ArrayList<String> = ArrayList() lng2.add("Objective c") lng2.add("Swift") techStackList.add(TechStackItem("IOS Development", lng2)) // on below line creating an array list for third tech tack and passing it to our tech stack list with tech stack name val lng3: ArrayList<String> = ArrayList() lng3.add("HTML") lng3.add("CSS") techStackList.add(TechStackItem("Web Development", lng3)) // on below line notifying adapter that data has changed. customListViewAdapter.notifyDataSetChanged() // on below line adding child click listener for expandable list view. expandableLV.setOnChildClickListener(OnChildClickListener { parent, v, groupPosition, childPosition, id -> // get the group header // on below line we are getting tech stack item from our tech stack list val techStackItem: TechStackItem = techStackList.get(groupPosition) // on below line we are getting our programming language item from tech stack item. val programmingLanguageItem: String = techStackItem.programmingLanguages.get(childPosition) // on below line we are displaying toast message Toast.makeText( baseContext, techStackItem.techStack + "/" + programmingLanguageItem, Toast.LENGTH_LONG ).show() false }) // on below line adding click listener for expandable list view. expandableLV.setOnGroupClickListener(OnGroupClickListener { parent, v, groupPosition, id -> // get the group header // on below line we are getting our tech stack item val techStackItem: TechStackItem = techStackList.get(groupPosition) // displaying toast message on below line. Toast.makeText(baseContext, techStackItem.techStack, Toast.LENGTH_LONG).show() false }) } }

Explanation > In the above code firstly we are creating variables for our techStack list for creating a new array list then we are creating a new variable for our adapter and after that we are creating a variable for expandable list view. After creating variables we are initializing all variables inside our on Create method. We are passing our list to our adapter and setting that adapter to our expandable list view.

After initializing our variables we are passing data to it. After that we are notifying the adapter that data within the list has been changed.

After setting data to our expandable list view, we are adding child click listener and group click listener for our expandable list view. Inside each method we are displaying a toast message to display on click on it.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note - Make sure you are connected to your real device or emulator.

Conclusion

In the above tutorial we learn What is Base Expandable List Adapter and How we can use it within our android application to display Expandable ListView within our android application.

Updated on: 14-Mar-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements