So I have a RadioButton in the RadioGroup that should be checked without resorting to using Id.
This my XML code:
<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>
Here I check the selected RadioButton:
RadioGroup radioGroup = findViewById(R.id.radioGroup);
int radioButtonId = radioGroup.getCheckedRadioButtonId();
switch (radioButtonId) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
}
I tried it:
1) Added attribute android:android:checkedButton to 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() is not executed because radioButtonId was not an index, but Id.
2) Then I added an attribute android:checked as "true" to my RadioButton.
<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() was executed, but now it was possible to checked both RadioButtons at the same time. The first RadioButton could not be unchecked. radioButtonId remained constant == 1.
I hope that you will tell me the correct way.
Thank you. Have a nice day.