ListView
定义
用于展示大量数据的一个控件,需要根据特定场景进行初始化。list集合中的数据无法直接传给控件,需要借助适配器,最好的适配器是ArrayAdapter。当集合数据为String类型(Int型)时,适配器的构造函数使用String类型(Int型)
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data)
其中括号内的第二个参数是子项布局的id,是安卓的内局部件
项目
注意:更改xml文件的布局为LinearLayout(如何更改查看更改操作)
主项目:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
class MainActivity : AppCompatActivity() {
lateinit var listview1: ListView
private val data= listOf("cat","dog","panda","lion","monkey","chick","tiger","fish","pig","rabbit","bird","horse","snake","mouse","elephant","sheep")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listview1=findViewById(R.id.listView)
val adapter=ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data)
listview1.adapter=adapter//将适配器传给adapter变量
}
}
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
效果
可以上下拖动(需要鼠标点击进行拖动,暂不能实现滚动)