适配器充当UI组件和数据源之间的桥梁。它将数据源中的数据转换为可以显示在UI组件中的视图项。在Android中,SimpleAdapter是一个简单的适配器,可以将静态数据映射到XML(布局)文件中定义的视图。您可以将支持列表的数据指定为Maps的ArrayList。 ArrayList中的每个条目对应于列表中的一行。地图包含每一行的数据。
为什么要使用CustomSimpleAdapter?
SimpleAdapter允许我们向每个列表项添加事件,但是如果我们想向列表项一部分的不同视图添加不同的事件怎么办,我们无法通过使用SimpleAdapter本身来实现。在典型的android应用程序中,列表项可以包含可能包含不同视图的复杂布局。在这种情况下,我们必须使用自定义SimpleAdapter。 SimpleAdapter的基本语法。
Syntax:
public SimpleAdapter(Context context, List extends Map
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.
SimpleAdapter的两个最重要的方法:
- getCount():此适配器表示的数据集中有多少个项目。
- getView():获取一个视图,该视图在数据集中的指定位置显示数据。您可以手动创建视图,也可以从XML布局文件中对其进行充气。当视图膨胀时,父视图(GridView,ListView…)将应用默认布局参数,除非您使用LayoutInflater.inflate(int,android.view.ViewGroup,boolean)指定根视图并防止附加到根。
例子
下面是我们将为本文创建的最终应用程序的gif。在此,您会注意到,单击list_item不会发生任何事情,但是当我们单击Image时,只会显示Toast。
逐步实施
步骤1:创建一个新项目
要在Android Studio中创建新项目,请参阅如何使用Kotlin在Android Studio中创建/启动新项目。我们将使用Kotlin 。
步骤2:使用activity_main.xml
现在打开activity_main.xml并在其中插入以下代码。它将创建一个由ListView组成的ConstraintLayout。以下是activity_main.xml文件的代码。
XML
XML
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>,
@LayoutRes
res: Int,
from: Array,
@IdRes
to: IntArray
) :
// Passing these params to SimpleAdapter
SimpleAdapter(mContext, data, res, from, to) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
// Get the view in our case list_item.xml
val view = super.getView(position, convertView, parent)
// Getting reference of ImageView that we
// have used in our list_item.xml file
// so that we can add user defined code
val avatarImageView = view.findViewById(R.id.avatarImageView)
// Reference of TextView which is treated a title
val titleTextView = view.findViewById(R.id.titleTextView)
// Adding an clickEvent to the ImageView, as soon as we click this
// ImageView we will see a Toast which will display a message
// Note: this event wil only fire when ImageView is pressed and
// not when whole list_item is pressed
avatarImageView.setOnClickListener {
Toast.makeText(
mContext,
"Image with title ${titleTextView.text} is pressed",
Toast.LENGTH_SHORT
).show()
}
// Finally returning our view
return view
}
}
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)
// Because SimpleAdapter works with static
// data so we need to initialize static data
// This is the array for TitleText
val titles = arrayOf("Test1", "Test2", "Test3")
// This array is for SubtitleText
val subtitles= arrayOf("This is test1 subtitle", "This is test2 subtitle", "This is test3 subtitle")
// These are the Id's of the images that will be displayed as avatar
val images = arrayOf(R.drawable.test1, R.drawable.test2, R.drawable.test3)
// Instantiating our data List, which is a list of HashMap
val data: MutableList> = mutableListOf()
// Populating our data List with the
// arrays that we have already defined
for (i in titles.indices) {
val cur: HashMap = HashMap()
cur["titleText"] = titles[i]
cur["subtitleText"] = subtitles[i]
cur["avatarImage"] = "${images[i]}"
data.add(cur)
}
// From and To array which will be used to map, HashMap values
// to the Views that are defined in the XML file (in our case list_item.xml)
val from = arrayOf("avatarImage", "titleText", "subtitleText")
val to = intArrayOf(R.id.avatarImageView, R.id.titleTextView, R.id.subtitleTextView)
// Instantiating customSimpleAdapter with the above values
val customSimpleAdapter = CustomSimpleAdapter(this, data, R.layout.list_item, from, to)
// Getting reference of listView which is defined in activity_main.xml
val listView = findViewById(R.id.listView)
// Finally, setting adapter to our customSimpleAdapter
listView.adapter = customSimpleAdapter
}
}
步骤3:为ListItem创建一个新的布局XML文件。
转到应用程序> res>布局>右键单击>新建>布局资源文件,然后创建一个XML文件。将该文件命名为list_item 。 下面是代码 list_item.xml文件。
XML格式
步骤4:实现CustomSimpleAdapter
现在创建一个新的Kotlin类文件,并将其命名为CustomSimpleAdapter 。在此文件中,我们将覆盖getView()方法以添加自定义代码。下面是代码 CustomSimpleAdapter.kt文件。在代码内部添加了注释,以更详细地了解代码。
科特林
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>,
@LayoutRes
res: Int,
from: Array,
@IdRes
to: IntArray
) :
// Passing these params to SimpleAdapter
SimpleAdapter(mContext, data, res, from, to) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
// Get the view in our case list_item.xml
val view = super.getView(position, convertView, parent)
// Getting reference of ImageView that we
// have used in our list_item.xml file
// so that we can add user defined code
val avatarImageView = view.findViewById(R.id.avatarImageView)
// Reference of TextView which is treated a title
val titleTextView = view.findViewById(R.id.titleTextView)
// Adding an clickEvent to the ImageView, as soon as we click this
// ImageView we will see a Toast which will display a message
// Note: this event wil only fire when ImageView is pressed and
// not when whole list_item is pressed
avatarImageView.setOnClickListener {
Toast.makeText(
mContext,
"Image with title ${titleTextView.text} is pressed",
Toast.LENGTH_SHORT
).show()
}
// Finally returning our view
return view
}
}
步骤5:使用MainActivity.kt文件
在MainActivity.kt文件中编写任何代码之前,请添加要显示的图像。下面是MainActivity.kt文件的代码。在代码内部添加了注释,以更详细地了解代码。
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)
// Because SimpleAdapter works with static
// data so we need to initialize static data
// This is the array for TitleText
val titles = arrayOf("Test1", "Test2", "Test3")
// This array is for SubtitleText
val subtitles= arrayOf("This is test1 subtitle", "This is test2 subtitle", "This is test3 subtitle")
// These are the Id's of the images that will be displayed as avatar
val images = arrayOf(R.drawable.test1, R.drawable.test2, R.drawable.test3)
// Instantiating our data List, which is a list of HashMap
val data: MutableList> = mutableListOf()
// Populating our data List with the
// arrays that we have already defined
for (i in titles.indices) {
val cur: HashMap = HashMap()
cur["titleText"] = titles[i]
cur["subtitleText"] = subtitles[i]
cur["avatarImage"] = "${images[i]}"
data.add(cur)
}
// From and To array which will be used to map, HashMap values
// to the Views that are defined in the XML file (in our case list_item.xml)
val from = arrayOf("avatarImage", "titleText", "subtitleText")
val to = intArrayOf(R.id.avatarImageView, R.id.titleTextView, R.id.subtitleTextView)
// Instantiating customSimpleAdapter with the above values
val customSimpleAdapter = CustomSimpleAdapter(this, data, R.layout.list_item, from, to)
// Getting reference of listView which is defined in activity_main.xml
val listView = findViewById(R.id.listView)
// Finally, setting adapter to our customSimpleAdapter
listView.adapter = customSimpleAdapter
}
}