所以我在 RadioGroup 中有一个 RadioButton,应该在不使用 Id 的情况下进行检查。
这是我的 XML 代码:
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 1" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 2" />
</RadioGroup>
在这里,我检查选定的 RadioButton:
RadioGroup radioGroup = findViewById(R.id.radioGroup);
int radioButtonId = radioGroup.getCheckedRadioButtonId();
switch (radioButtonId) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
}
我尝试过这个:
1) 向 RadioGroup 添加属性 android:android:checkedButton。
<RadioGroup
android:id="@+id/radioGroup"
android:checkedButton="@id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 1" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 2" />
</RadioGroup>
doSometheing() 未执行,因为 radioButtonId 不是索引,而是 Id。
2)然后我在我的 RadioButton 中添加了一个属性 android:checked 为“true”。
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton 1" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton 2" />
</RadioGroup>
doSometheing() 已执行,但现在可以同时检查两个 RadioButton。无法取消选中第一个 RadioButton。radioButtonId 保持不变 == 1。
我希望你能告诉我正确的方法。
谢谢你。祝你今天过得愉快。
您可以获得checked
RadioButton
如下索引:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
switch (idx) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
}
注意:不要忘记id
为radio buttons
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句