【发布时间】:2019-08-29 17:58:55
【问题描述】:
所以我在 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) 添加属性 android:android:checkedButton 到 RadioGroup。
<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 as "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。
希望你能告诉我正确的方法。
谢谢。祝你有美好的一天。
【问题讨论】:
-
为什么你不想为
radio button提供id?每个组件都应该有一个id。 -
@AbuNoman,很可能,这是正确的方法。但是当 ID 很多时,我害怕在 ID 中感到困惑。我更喜欢索引。如果我错了,请告诉我。
标签: java android android-studio