Android | RadioGroup--设置默认选中

RadioGroup 中, 是通过RadioButton 的 id 来控制是否选中。

1. 布局文件中控制:

如果在xml 布局文件中需要控制一个RadioButton 默认选中,就需要给他设置一个id。如果不设置id 的话,就会导致该RadioButton 一直是选中状态。代码如下:

 <RadioGroup
        android:id="@+id/rg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
    <!--该RadioButton 需要设置默认选中,所以给出id-->    
    <RadioButton
        android:id="@+id/rb1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/selector_bk_rb"
        android:button="@null"
        android:checked="true"
        android:gravity="center"
        android:padding="10dp"

    <RadioButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/selector_bk_rb"
        android:button="@null"
        android:gravity="center"
        android:padding="10dp"
        android:text="第2 个button"/>
    <RadioButton
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/selector_bk_rb"
        android:button="@null"
        android:gravity="center"
        android:padding="10dp"
        android:text="第3 个button"/>

2. 代码控制

很多时候,我们需要在代码中动态的 添加 RadioButton 到RadioGroup ,这时候,如果想设置某个RadioButton 的默认选中,就需要先通过 getId( ) 获取 radioButton 的id,然后再去设置。方式也有两种,一种是通过id 获取view 后去设置;一种是使用 radiogroup.check( id ) 直接设置。具体如下:

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

        for (int i = 0; i < 12; i++) {
            RadioButton radioButton = new RadioButton(getContext());
            radioButton.setButtonDrawable(null);
            radioButton.setBackgroundResource(R.drawable.selector_bk_rb);
            radioButton.setText("Button" + i);
            radioButton.setPadding(15, 15, 15, 15);
            radioButton.setTextSize(20);
            radioGroup.addView(radioButton);

            if (i == 0) {
                //                // 设置默认选中方式1 ,先获取控件,然后设置选中               
                //                //根据id 获取radioButton 控件
                //                RadioButton rb_checked = (RadioButton) radioGroup.findViewById(radioButton.getId());
                //                //设置默认选中
                //                rb_checked.setChecked(true);

                // 设置默认选中方式2                
                radioGroup.check(radioButton.getId());
            }
        }
  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CnPeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值