RadioButton和CheckBox

一:RadioButton

RadioButton为单选按钮,需要和RadioGroup组合使用
主要目的:获取用户选择的按钮的值


1.获取RadioGroup控件

 radioGroup = (RadioGroup)findViewById(R.id.radiogroup1);

2.为radioGroup添加监听事件

      radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                //第二个参数i为被选取的RadioButton 资源ID
                // ID已可以这样获取 int id = radioGroup.getCheckedRadioButtonId();

                radioButton = (RadioButton)findViewById(i);
                tv.setText(radioButton.getText());
            }
        });


1)方法getCheckedRadioButtonId()

获取选中RadioButton的ID
2)onCheckedChanged()第二个参数是返回被选取RadioButton的资源ID


二:复选框CheckBox

CheckBox和RadioButton不同(一次只能选取一项),复选框一次可以复选多个
目的:要对每一个checkBox做出监听,获取选中和取消的状态

//复选框的资源ID数组
        int[] check_id = {R.id.box1, R.id.box2, R.id.box3, R.id.box4};
        for(int id:check_id){
            CheckBox chk = (CheckBox)findViewById(id);
            chk.setOnCheckedChangeListener(checklistener);//对每一个checkBox注册监听对象
        }
    }
        ArrayList<CompoundButton> selected = new ArrayList<>(); //存放被选中的checkbox组件

    private CompoundButton.OnCheckedChangeListener checklistener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //参数compoundButton 为被选中的checkbox
                //参数b 是isChecked是否被选中
                //tvbox.setText("你选中了"+compoundButton.getText().toString());输出单个选中项
                String msg = "";
                if(b){
                    selected.add(compoundButton); //若选中则添加到集合
                    for(CompoundButton chk:selected)
                        msg += "\n"+chk.getText().toString();

                    tvbox.setText("你选中了"+msg);
                }else{
                    selected.remove(compoundButton);//若取消则移除集合
                    tvbox.setText("你取消了"+compoundButton.getText().toString());

                }
        }
    };

onCheckedChanged()方法第一个参数是被触发的checkBox,第二个是触发的状态


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值