问题:
单选按钮选中一次后设置setChecked(true)为选中状态,下一次回到该界面,单选按钮却是未选中状态
<RadioGroup
android:id="@+id/rg_single_choice"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="@+id/rb_single_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/rb_single_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/rb_single_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="@+id/rb_single_d"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
//清空控件选中状态
/**
rbSingleA.setChecked(false);
rbSingleB.setChecked(false);
rbSingleC.setChecked(false);
rbSingleD.setChecked(false);
**/
rgSingleChioce.clearCheck();
String answer = answers[questionIndex];//记录选中的编号
if (answer != null) {
//根据用户答案来设定单选按钮状态
switch (answer) {
case "A":
rbSingleA.setChecked(true);
break;
case "B":
rbSingleB.setChecked(true);
break;
case "C":
rbSingleC.setChecked(true);
break;
case "D":
rbSingleD.setChecked(true);
break;
}
}
清空控件选中状态时,有两种方法:
第一种:(错误)
第二种:(正确)
多次调用setChecked(false)会出问题,多次调用后就会导致下次点击不会变为选中状态,可以调用RadioGroup的clearCheck()方法清空控件选中状态
原因:
因为你只设置了radiobutton的属性,并没有设置radiogroup的属性,所以对于radiogroup来说,它并不知道你的radiobutton已经设置成了false.