Android中的ListView

ListView

kotlin属性 数据类型 说明
adapter Adapter类 适配器,ListView将以该配置为模板显示内容

用法:

1
2
3
4
5
6
val data = arrayOf("角木蛟", "亢金龙", "尾火虎", "箕水豹")

// 构造函数的参数,第一个是上下文对象Context,第二个是适配器Adapter,第三个是要传进ListView展示的数据
val adapter = ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, data)
val listView = findViewById<ListView>(R.id.listview)
listView.adapter = adapter

这里的android.R.layout.simple_expandable_list_item_1还可以改用其他Adapter适配器。

ArrayAdapter

  • simple_list_item_1

simple_list_item_1

  • simple_list_item_2

simple_list_item_2

  • simple_list_item_single_choice

simple_list_item_single_choice

  • simple_list_item_multiple_choice

simple_list_item_multiple_choice

  • simple_list_item_checked

simple_list_item_checked

SimpleAdapter

SimpleAdapter 允许你写一个布局,然后ListView中的所有行都使用这个布局。基本能实现任意效果。

res/layout/list_item.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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:paddingStart="20dp"
android:paddingEnd="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:orientation="vertical">

<TextView
android:id="@+id/list_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold" />

<TextView
android:id="@+id/list_item_description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

java/MainActivity.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 要显示的数据
val title = arrayOf("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天")
val description = arrayOf("周一周一,奄奄一息", "周二周二,肚子好饿", "周三周三,带病上班", "周四周四,重见天日", "周五周五,敲锣打鼓", "周六周六,大鱼大肉", "周日周日,死期将至")

// Adapter要的数据是一个List,List里每个Map对应一行,Map里一个键值对即一个要显示的数据
val datas = mutableListOf<Map<String, String>>()
for (i in title.indices) {
val map = hashMapOf("title" to title[i], "description" to description[i])
datas.add(map)
}

val adapter = SimpleAdapter(
this, // 上下文 Context
datas, // 数据
R.layout.list_item, // 布局文件,每一行按该布局文件布局
arrayOf<String>("title", "description"), // 有哪些数据
intArrayOf(R.id.list_item_title, R.id.list_item_description) // 对应上一行,将数据放到布局文件中的哪里
)

效果如下:

simple_adapter