My requirement is to be able to be able to check only 1 radio button from the no of options available.
My layout is simple

User should be able to select only one of p1, p2 and p3.
The IDs for for the buttons are rB1,rB2 and rB3.
PS: I know it is possible to achieve the same with RadioGroup , but in this particular instance I want to go with Radio Button hence the query
Try this..
r1.setOnCheckedChangeListener(this);
r2.setOnCheckedChangeListener(this);
r3.setOnCheckedChangeListener(this);
And CheckedChangeListener
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (buttonView.getId() == R.id.rB1) {
r2.setChecked(false);
r3.setChecked(false);
}
if (buttonView.getId() == R.id.rB2) {
r1.setChecked(false);
r3.setChecked(false);
}
if (buttonView.getId() == R.id.rB3) {
r1.setChecked(false);
r2.setChecked(false);
}
}
}
and don't forget to implements OnCheckedChangeListener in your activity or fragment.
Use Radio group
XML:
<RadioGroup
android:id="@+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/rB1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P1"
android:checked="true" />
<RadioButton
android:id="@+id/rB2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P2" />
<RadioButton
android:id="@+id/rB3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P3" />
</RadioGroup>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With