ListView的单选和多选模式
在使用ListView的时候,我们有时需要使用ListView提供的选择模式,如有时候删除一个列表的多个选项的时候(多选模式),选择一个列表的某一项的时候(单选模式)。android提供了单选和多选模式供我们使用。
在使用的时候通过setChoiceMode();来选择单选或多选模
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);//开启多选式
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);//开启单选模式
具体实现:
首先声明一个xml文件,并在其中声明一个ListView 指明其属性
<?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="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView3"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
在主Activity文件中声明数据源,适配器,以及选择模式等属性如下:
public class MyActivity3 extends Activity {
private ListView lv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
lv = (ListView) findViewById(R.id.listView3);
String[] citys = { "北京", "上海", "广州", "深圳" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, citys);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);// 设置为单选模式
lv.setAdapter(adapter);
}
在模拟器上测试如下:
每次只能单击选择一个
多选模式如下:
在上面的.java文件中,只需将原来的单选模式改为多选模式即可。
如下:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, citys);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
测试结果如下: