Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio Button checking and unchecking programmatically in android

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

enter image description here

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

like image 508
misguided Avatar asked Dec 04 '25 01:12

misguided


2 Answers

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.

like image 182
Hariharan Avatar answered Dec 05 '25 16:12

Hariharan


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>
like image 36
Madhu Avatar answered Dec 05 '25 16:12

Madhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!