Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

BaseExpandableListAdapter in Android with Example

BaseExpandableListAdapter is an abstract class in Android that facilitates creating an ExpandableListView where data is organized in groups and children. Each group can be expanded or collapsed to show or hide its children.

To use the BaseExpandableListAdapter, you must subclass it and implement its methods to provide data for groups and children.

Example:

Let's create a simple ExpandableListView with countries as groups and their cities as children.

  • XML Layout (res/layout/activity_main.xml):
<ExpandableListView
    android:id="@+id/expandableListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  • Custom Adapter:

Create a custom adapter by extending BaseExpandableListAdapter:

class CustomExpandableListAdapter(
    private val context: Context,
    private val groupList: List<String>,
    private val childList: HashMap<String, List<String>>
) : BaseExpandableListAdapter() {

    override fun getGroupCount(): Int {
        return groupList.size
    }

    override fun getChildrenCount(groupPosition: Int): Int {
        return childList[groupList[groupPosition]]?.size ?: 0
    }

    override fun getGroup(groupPosition: Int): Any {
        return groupList[groupPosition]
    }

    override fun getChild(groupPosition: Int, childPosition: Int): Any {
        return childList[groupList[groupPosition]]!![childPosition]
    }

    override fun getGroupId(groupPosition: Int): Long {
        return groupPosition.toLong()
    }

    override fun getChildId(groupPosition: Int, childPosition: Int): Long {
        return childPosition.toLong()
    }

    override fun hasStableIds(): Boolean {
        return false
    }

    override fun getGroupView(
        groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?
    ): View {
        var view = convertView
        if (view == null) {
            val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            view = inflater.inflate(android.R.layout.simple_expandable_list_item_1, null)
        }
        (view as TextView).text = getGroup(groupPosition) as String
        return view
    }

    override fun getChildView(
        groupPosition: Int, childPosition: Int, isLastChild: Boolean,
        convertView: View?, parent: ViewGroup?
    ): View {
        var view = convertView
        if (view == null) {
            val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            view = inflater.inflate(android.R.layout.simple_list_item_1, null)
        }
        (view as TextView).text = getChild(groupPosition, childPosition) as String
        return view
    }

    override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
        return true
    }
}
  • Using the Custom Adapter in Activity:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val groupList = listOf("USA", "Canada")
        val childList = hashMapOf(
            "USA" to listOf("New York", "Los Angeles", "Chicago"),
            "Canada" to listOf("Toronto", "Vancouver", "Montreal")
        )

        val adapter = CustomExpandableListAdapter(this, groupList, childList)
        val expandableListView: ExpandableListView = findViewById(R.id.expandableListView)
        expandableListView.setAdapter(adapter)
    }
}

In this example, the ExpandableListView displays countries (USA and Canada) as groups. When a group is clicked, it shows the cities within that country.

This is a basic example. For more customized displays, you can design custom layouts for the group and child views and inflate them in the getGroupView and getChildView methods, respectively.

  1. Using BaseExpandableListAdapter in Android Kotlin:

    • Description: BaseExpandableListAdapter is an abstract class that facilitates the implementation of adapters for ExpandableListViews in Android. It provides methods to handle data and view binding for groups and children.
    • Code (Kotlin):
      class MyExpandableListAdapter : BaseExpandableListAdapter() {
          // Implement required methods for groups and children
      }
      
  2. ExpandableListView with BaseExpandableListAdapter example:

    • Description: An example showcasing the usage of ExpandableListView with a custom BaseExpandableListAdapter.
    • Code (Kotlin):
      val expandableListView = findViewById<ExpandableListView>(R.id.expandableListView)
      val adapter = MyExpandableListAdapter()
      expandableListView.setAdapter(adapter)
      
  3. Customizing BaseExpandableListAdapter in Android:

    • Description: Extend BaseExpandableListAdapter to create a customized adapter tailored to specific data and view requirements.
    • Code (Kotlin):
      class CustomExpandableListAdapter : BaseExpandableListAdapter() {
          // Implement custom methods and override necessary functions
      }
      
  4. Adding groups and children with BaseExpandableListAdapter:

    • Description: Implement methods like getGroup and getChild to provide data for groups and children in the ExpandableListView.
    • Code (Kotlin):
      override fun getGroup(groupPosition: Int): Any {
          // Return group data based on position
      }
      
      override fun getChild(groupPosition: Int, childPosition: Int): Any {
          // Return child data based on group and child positions
      }
      
  5. Handling click events in BaseExpandableListAdapter:

    • Description: Use onGroupClick and onChildClick methods to handle click events for groups and children.
    • Code (Kotlin):
      override fun onGroupClick(
          parent: ExpandableListView?,
          v: View?,
          groupPosition: Int,
          id: Long
      ): Boolean {
          // Handle group click event
          return true
      }
      
      override fun onChildClick(
          parent: ExpandableListView?,
          v: View?,
          groupPosition: Int,
          childPosition: Int,
          id: Long
      ): Boolean {
          // Handle child click event
          return true
      }
      
  6. Populating ExpandableListView with BaseExpandableListAdapter:

    • Description: Populate the ExpandableListView by providing data through the overridden methods like getGroupCount and getChildrenCount.
    • Code (Kotlin):
      override fun getGroupCount(): Int {
          // Return the total number of groups
      }
      
      override fun getChildrenCount(groupPosition: Int): Int {
          // Return the number of children in a specific group
      }
      
  7. Implementing a collapsible list in Android with BaseExpandableListAdapter:

    • Description: Achieve a collapsible list by implementing methods like isChildSelectable and isGroupSelectable.
    • Code (Kotlin):
      override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
          // Return true if the child is selectable
      }
      
      override fun isGroupSelectable(groupPosition: Int): Boolean {
          // Return true if the group is selectable
      }
      
  8. Updating data dynamically with BaseExpandableListAdapter:

    • Description: Allow dynamic updates to the data by modifying the underlying dataset and notifying the adapter using methods like notifyDataSetChanged.
    • Code (Kotlin):
      fun updateData(newData: List<GroupData>) {
          // Update the dataset
          dataSet = newData
          // Notify the adapter about the changes
          notifyDataSetChanged()
      }