SimpleAdapter主容器
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".SimpleActivity">
<ListView
android:id="@+id/list_view2"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
Item布局
<?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">
<ImageView
android:id="@+id/qq_img"
android:layout_width="50dp"
android:layout_height="65dp"
android:background="@mipmap/caocao"/>
<TextView
android:id="@+id/qq_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/qq_img"
android:layout_marginLeft="5dp"
android:textSize="26sp"
android:text="Caocao" />
<TextView
android:id="@+id/qq_mood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/qq_img"
android:layout_below="@id/qq_name"
android:layout_marginLeft="5dp"
android:textColor="#2ae0c8"
android:text="xixixi"/>
</RelativeLayout>
配置SimpleAdapter
package com.example.fragmentapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ListView
import android.widget.SimpleAdapter
import android.widget.Toast
import java.util.ArrayList
import java.util.HashMap
class SimpleActivity : AppCompatActivity() {
private val data: MutableList<Map<String, Any>> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_simple)
val listView2 = findViewById<ListView>(R.id.list_view2)
initData()
val from = arrayOf<String?>("img", "name", "mood")
val to = intArrayOf(R.id.qq_img, R.id.qq_name, R.id.qq_mood)
val adapter = SimpleAdapter(this, data, R.layout.item3, from, to)
listView2.adapter = adapter
listView2.setOnItemClickListener {
adapterView, view, i, l ->
val map: Map<String, Any>? = data[i]
val name = map!!["name"].toString()
val mood = map["mood"].toString()
Toast.makeText(this@SimpleActivity, "$name $mood", Toast.LENGTH_SHORT).show()
}
}
private fun initData() {
val map1: MutableMap<String, Any> = HashMap()
map1["img"] = R.mipmap.caocao
map1["name"] = "曹操"
map1["mood"] = "宁教我负天下人,休教天下人负我"
val map2: MutableMap<String, Any> = HashMap()
map2["img"] = R.mipmap.zhenji
map2["name"] = "甄姬"
map2["mood"] = "飘摇兮若流风之回雪,仿佛兮若轻云之蔽月"
data.add(map1)
data.add(map2)
}
}