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

Custom SimpleAdapter in Android with Example

The SimpleAdapter is another type of adapter in Android which is usually used to bind data to views such as ListView using a more complex layout than just a simple text view, but without the need to define a custom adapter class.

However, sometimes you need to make slight modifications to the behavior of the SimpleAdapter. For this, you can extend the SimpleAdapter class.

1. Data Preparation

Let's consider a scenario where we want to display a list of users with their names and email addresses:

val users = listOf(
    mapOf("name" to "John Doe", "email" to "john@example.com"),
    mapOf("name" to "Jane Smith", "email" to "jane@example.com")
)

2. Define the Layout

Create a layout user_item.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="wrap_content"
    android:padding="16dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/userEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"/>

</LinearLayout>

3. Create the Custom SimpleAdapter

class CustomSimpleAdapter(context: Context, data: List<Map<String, String>>, resource: Int, from: Array<String>, to: IntArray) 
    : SimpleAdapter(context, data, resource, from, to) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = super.getView(position, convertView, parent)
        
        // Any custom modification to the view can be done here
        // For instance, changing text colors, backgrounds, etc.

        return view
    }
}

4. Use the CustomSimpleAdapter

In your activity:

val from = arrayOf("name", "email")
val to = intArrayOf(R.id.userName, R.id.userEmail)

val adapter = CustomSimpleAdapter(this, users, R.layout.user_item, from, to)
val listView: ListView = findViewById(R.id.listView)
listView.adapter = adapter

With this setup, you've created a custom SimpleAdapter to modify the views within a ListView while still leveraging the convenience of the SimpleAdapter. This method is particularly useful when you only need minor adjustments to the default behavior. If you require significant customizations, consider using a custom ArrayAdapter instead.

  1. Creating a custom layout for SimpleAdapter in Android Kotlin:

    • Description: Creating a custom layout for SimpleAdapter involves designing a layout XML file that defines the appearance of each item in the ListView. This layout will be inflated for each item in the SimpleAdapter.
    • Code (XML):
      <!-- Example of a custom layout for SimpleAdapter -->
      <!-- custom_item_layout.xml -->
      <LinearLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical">
      
          <TextView
              android:id="@+id/textView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Item Text" />
      
          <ImageView
              android:id="@+id/imageView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/default_image" />
      
      </LinearLayout>
      
  2. Customizing SimpleAdapter in Android for custom layouts:

    • Description: Customizing SimpleAdapter for custom layouts involves extending SimpleAdapter and providing a custom layout for each item in the adapter. This allows you to control the appearance of each item in the ListView.
    • Code (Kotlin):
      // Example of customizing SimpleAdapter for custom layouts
      class CustomSimpleAdapter(
          context: Context,
          data: List<Map<String, Any>>,
          resource: Int,
          from: Array<String>,
          to: IntArray
      ) : SimpleAdapter(context, data, resource, from, to) {
      
          override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
              val inflater = LayoutInflater.from(context)
              val customView = inflater.inflate(R.layout.custom_item_layout, parent, false)
              val itemData = getItem(position) as Map<String, Any>
      
              val textView: TextView = customView.findViewById(R.id.textView)
              val imageView: ImageView = customView.findViewById(R.id.imageView)
      
              textView.text = itemData["text"]?.toString()
              imageView.setImageResource(itemData["imageRes"] as Int)
      
              return customView
          }
      }
      
  3. Populating ListView with Custom SimpleAdapter in Android:

    • Description: Populating a ListView with a Custom SimpleAdapter involves creating an instance of the adapter and setting it to the ListView. The adapter is responsible for providing the views for each item in the list.
    • Code (Kotlin):
      // Example of populating ListView with Custom SimpleAdapter
      val customData = listOf(
          mapOf("text" to "Item 1", "imageRes" to R.drawable.image1),
          mapOf("text" to "Item 2", "imageRes" to R.drawable.image2),
          mapOf("text" to "Item 3", "imageRes" to R.drawable.image3)
      )
      
      val from = arrayOf("text", "imageRes")
      val to = intArrayOf(R.id.textView, R.id.imageView)
      
      val customSimpleAdapter = CustomSimpleAdapter(this, customData, R.layout.custom_item_layout, from, to)
      val listView: ListView = findViewById(R.id.listView)
      listView.adapter = customSimpleAdapter
      
  4. Handling click events with Custom SimpleAdapter:

    • Description: Handling click events with Custom SimpleAdapter involves setting an item click listener on the ListView. This allows you to respond to user clicks on individual items.
    • Code (Kotlin):
      // Example of handling click events with Custom SimpleAdapter
      listView.setOnItemClickListener { parent, view, position, id ->
          // Handle click on item at position
          val selectedItemData = customData[position]
          // Perform actions based on the clicked item
      }
      
  5. Using SimpleAdapter with custom data in Android:

    • Description: Using SimpleAdapter with custom data involves providing a List of Map objects, where each Map represents the data for a single item in the ListView. The keys in the Map correspond to the keys specified in the "from" parameter.
    • Code (Kotlin):
      // Example of using SimpleAdapter with custom data
      val customData = listOf(
          mapOf("text" to "Item 1", "imageRes" to R.drawable.image1),
          mapOf("text" to "Item 2", "imageRes" to R.drawable.image2),
          mapOf("text" to "Item 3", "imageRes" to R.drawable.image3)
      )
      
      val from = arrayOf("text", "imageRes")
      val to = intArrayOf(R.id.textView, R.id.imageView)
      
      val simpleAdapter = SimpleAdapter(this, customData, R.layout.custom_item_layout, from, to)
      val listView: ListView = findViewById(R.id.listView)
      listView.adapter = simpleAdapter
      
  6. Customizing text and images in Custom SimpleAdapter:

    • Description: Customizing text and images in Custom SimpleAdapter involves updating the layout and populating views with text and image data from the underlying data source.
    • Code (Kotlin):
      // Example of customizing text and images in Custom SimpleAdapter
      class CustomSimpleAdapter(
          context: Context,
          data: List<Map<String, Any>>,
          resource: Int,
          from: Array<String>,
          to: IntArray
      ) : SimpleAdapter(context, data, resource, from, to) {
      
          override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
              val inflater = LayoutInflater.from(context)
              val customView = inflater.inflate(R.layout.custom_item_layout, parent, false)
              val itemData = getItem(position) as Map<String, Any>
      
              val textView: TextView = customView.findViewById(R.id.textView)
              val imageView: ImageView = customView.findViewById(R.id.imageView)
      
              textView.text = itemData["text"]?.toString()
              imageView.setImageResource(itemData["imageRes"] as Int)
      
              return customView
          }
      }
      
  7. Sorting data with Custom SimpleAdapter in Android:

    • Description: Sorting data with a Custom SimpleAdapter involves implementing sorting logic within the adapter. This can be achieved by modifying the data source and notifying the adapter of the changes.
    • Code (Kotlin):
      // Example of sorting data with Custom SimpleAdapter
      fun sortData() {
          customData.sortBy { it["text"]?.toString() }
          customSimpleAdapter.notifyDataSetChanged()
      }
      
  8. Dynamic data updates with Custom SimpleAdapter:

    • Description: Dynamically updating data with a Custom SimpleAdapter involves modifying the underlying data source and notifying the adapter of the changes. This ensures that the ListView reflects the latest data.
    • Code (Kotlin):
      // Example of dynamic data updates with Custom SimpleAdapter
      fun updateData(newData: List<Map<String, Any>>) {
          customData.clear()
          customData.addAll(newData)
          customSimpleAdapter.notifyDataSetChanged()
      }