ListView的单选和多选模式的使用

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);

测试结果如下:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值