Custom SimpleAdapter in Android with Example
Last Updated :
10 Oct, 2022
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. In Android, SimpleAdapter is an easy adapter to map static data to views defined in an XML (layout) file. You can specify the data backing the list as an ArrayList of Maps. Each entry in the ArrayList corresponds to one row in the list. The Maps contain the data for each row.
Why use CustomSimpleAdapter?
SimpleAdapter allows us to add events to each list item but what if we want to add different events to different views that are part of our list item, we cannot achieve it by using SimpleAdapter itself. In a typical android application, a list item can consist of a complex layout that may contain different views. In that condition, we have to use customize SimpleAdapter. The basic syntax of SimpleAdapter.
Syntax:
public SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
Parameters:
context: The context where the View associated with this SimpleAdapter is running
data: A List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row, and should include all the entries specified in “from”
resource: Resource identifier of a view layout that defines the views for this list item. The layout file should include at least those named views defined in “to”
from: A list of column names that will be added to the Map associated with each item.
to: The views that should display column in the “from” parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter.
Two most important methods of SimpleAdapter:
- getCount(): How many items are in the data set represented by this Adapter.
- getView(): Get a view that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file. When the View is inflated, the parent View (GridView, ListView…) will apply default layout parameters unless you use LayoutInflater.inflate(int, android.view.ViewGroup, boolean) to specify a root view and to prevent attachment to the root.
Example
Below is the gif of the final application that we are going to create for this article. In this, you will notice that by clicking list_item nothing happens but when we click on Image then only Toast is displayed.
Step by step implementation
Step 1: Create a new Project
To create a new Project in Android Studio please refer to How to Create/Start a New Project in Android Studio using Kotlin. We are going to use Kotlin.
Step 2: Working with the activity_main.xml
Now open activity_main.xml and insert the below code in it. It will create a ConstraintLayout which consists of a ListView. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< ListView
android:id = "@+id/listView"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</ androidx.constraintlayout.widget.ConstraintLayout >
|
Step 3: Creating a new layout XML file for ListItem.
Go to the app > res > layout > right-click > New > Layout Resource File and creates a XML file. Name the file as list_item. Below is the code for the list_item.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:id = "@+id/mainLayout"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:padding = "2dp" >
< ImageView
android:id = "@+id/avatarImageView"
android:layout_width = "65dp"
android:layout_height = "65dp"
android:clickable = "true"
android:focusable = "true"
tools:srcCompat = "@tools:sample/avatars" />
< LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:layout_marginStart = "4dp"
android:orientation = "vertical" >
< TextView
android:id = "@+id/titleTextView"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "bold"
tools:text = "Title" />
< TextView
android:id = "@+id/subtitleTextView"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:ellipsize = "end"
android:gravity = "center_vertical"
android:maxLines = "2"
tools:text = "Subtitle" />
</ LinearLayout >
</ LinearLayout >
|
Step 4: Implementing CustomSimpleAdapter
Now create a new Kotlin class file and name it CustomSimpleAdapter. In this file, we will override the getView() method to add the custom code. Below is the code for the CustomSimpleAdapter.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.SimpleAdapter
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
class CustomSimpleAdapter(
private val mContext: Context,
data: MutableList<HashMap<String, String>>,
@LayoutRes
res: Int,
from: Array<String>,
@IdRes
to: IntArray
) :
SimpleAdapter(mContext, data, res, from, to) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = super .getView(position, convertView, parent)
val avatarImageView = view.findViewById<ImageView>(R.id.avatarImageView)
val titleTextView = view.findViewById<TextView>(R.id.titleTextView)
avatarImageView.setOnClickListener {
Toast.makeText(
mContext,
"Image with title ${titleTextView.text} is pressed" ,
Toast.LENGTH_SHORT
).show()
}
return view
}
}
|
Step 5: Working with the MainActivity.kt file
Before writing any code in MainActivity.kt file please add images that you want to show. Below is the code for MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val titles = arrayOf( "Test1" , "Test2" , "Test3" )
val subtitles= arrayOf( "This is test1 subtitle" , "This is test2 subtitle" , "This is test3 subtitle" )
val images = arrayOf(R.drawable.test1, R.drawable.test2, R.drawable.test3)
val data: MutableList<HashMap<String, String>> = mutableListOf()
for (i in titles.indices) {
val cur: HashMap<String, String> = HashMap()
cur[ "titleText" ] = titles[i]
cur[ "subtitleText" ] = subtitles[i]
cur[ "avatarImage" ] = "${images[i]}"
data.add(cur)
}
val from = arrayOf( "avatarImage" , "titleText" , "subtitleText" )
val to = intArrayOf(R.id.avatarImageView, R.id.titleTextView, R.id.subtitleTextView)
val customSimpleAdapter = CustomSimpleAdapter( this , data, R.layout.list_item, from, to)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = customSimpleAdapter
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...