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