1.xml文件中添加ListView
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/data_list"
android:divider="@color/colorPrimary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_home"/>
2.声明adapter
package com.example.myapplication.ui.adapter
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.example.myapplication.R
class DataListDataAdapter(var context:Context?,var dataList: MutableList<String>) : BaseAdapter() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val holder:ViewHolder;
val layout:View
if (convertView==null) {
holder = ViewHolder()
layout = View.inflate(context,R.layout.list_item,null)
holder.iconInfo = layout.findViewById(R.id.icon_info)
holder.textInfo = layout.findViewById(R.id.text_info)
holder.textInfo!!.text = dataList[position]
layout.tag = holder
} else {
layout = convertView
holder = convertView.tag as ViewHolder
}
return layout
}
override fun getItem(position: Int): Any {
return dataList[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return dataList.size
}
inner class ViewHolder{
var iconInfo: ImageView? = null
var textInfo: TextView? = null
}
}
3.item布局
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:id="@+id/icon_info"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_info"
android:text="Hello Kotlin"
android:textSize="20sp"
android:layout_marginStart="20dp"
app:layout_constraintLeft_toRightOf="@+id/icon_info"
app:layout_constraintTop_toTopOf="@+id/icon_info"
app:layout_constraintBottom_toBottomOf="@+id/icon_info"/>
</androidx.constraintlayout.widget.ConstraintLayout>
4.ListView绑定数据
listView = root.findViewById(R.id.data_list)
var list:MutableList<String> = mutableListOf()
list.add("Hello")
list.add("Kotlin")
list.add("Come on")
val adapter = DataListDataAdapter(context,list)
listView.adapter = adapter
5.效果
Screenshot_1609815336.png