ListView的Item中包含RadioButton的使用

本文介绍如何在Android的ListView中实现单选效果。通过设置listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE)来使ListView支持单选模式,并在Adapter中通过监听RadioButton的状态变化来控制ListView中仅能有一个选项被选中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更新:

可以使用listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);实现

多个RadioButton必须放在同一个RadioGroup中才有单选效果,但是在ListView的item中包含呢?

在Adapter中:

private int mCheckedPosition = -1;//默认不选中任何RadioButton
//下面是关键
mHolder.couponRBChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        //确保只有一项被选中,并且setChecked方法会触发onCheckedChanged的调用,所以只有在b为true,即RadioButton被选中的情况下才更新列表
        if(b) {
            mCheckedPosition = position;
            notifyDataSetChanged();
        }
    }
});
mHolder.couponRBChecked.setChecked(mCheckedPosition == position);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值