ListView是Android系统absListView的子类。以列表形式来展示数据将数据填充到布局中
开发应用程序时,使用ListView有两个常用功能:
1、将数据填充到对应布局中
2、处理用户选择的点击操作
我们的布局可以只有一个ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
以数组为数据源的操作
String[] str = {"张三","李四","王五","赵六"};
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity01.this, android.R.layout.simple_list_item_multiple_choice,str);
ArrayAdapter的三个参数(@NonNull Context context, @LayoutRes int resource, @NonNull T[] objects)
第一个参数:上下文对象;
第二个参数:布局资源文件
第三个参数:数据源
将适配器与我们的列表进行绑定即可
//将适配器与列表进行绑定
lv.setAdapter(arrayAdapter);
上面我使用的是Android自带的布局,点击去看可以发现这是一个有多选框的布局
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" />
但是我们此时点击这个多选框并没有效果,所以我们还需要对它进行点击处理
//设置可以点击的选项框
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ListView单击事件
//ListView的单机事件
lv.setOnItemClickListener((parent,view,Position,id)->{
/*
* AdapterView<?> parent:表示事件发生的AdapterView(ListView绑定在适配器中的某一行)
* View view:表示你单击或长按的ListView的某一项View
* int Position:表示你单击或长按的这一项在Adapter中的位置
* long id:表示你单机或长按的这一项在ListView中的位置
* */
//获取LIstView列表中别选中的对象
SparseBooleanArray booleanArray = lv.getCheckedItemPositions();
String temp = "";
for (int i = 0; i < str.length; i++) {
if (booleanArray.get(i)){
temp = temp +","+str[i];
}
}
Toast.makeText(MainActivity.this,temp,Toast.LENGTH_LONG).show();
});