Search code examples
androidradio-buttonradio-group

How to uncheck a radio button in another radio group?


I have two radio groups in one xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

       <RadioButton
            android:id="@+id/btn_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

        <RadioButton
            android:id="@+id/btn_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

    </RadioGroup>

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/btn_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

        <RadioButton
            android:id="@+id/btn_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked" />

    </RadioGroup>

</LinearLayout>

In the main activity I can handle radio buttons on click listener by implementing the onRadioButtonClicked() method:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.btn_1:

            break;
        case R.id.R.id.btn_2: 

            break;
        case R.id.R.id.btn_3: 

            break;
        case R.id.R.id.btn_4: 

            break;
    }
}

Now, in the same radio group if a radio button is checked, the other is unchecked automatically. So here is my problem: I want that if a button is checked the other buttons in the same group and in the other group to be unchecked. Is this doable? Thanks.


Solution

  • You can do it manually .

    case R.id.btn_1:
       btn3.setChecked(false);
       btn4.setChecked(false);
      break;
    case R.id.btn_2:
       btn3.setChecked(false);
       btn4.setChecked(false);
      break;
    case R.id.btn_3:
       btn1.setChecked(false);
       btn2.setChecked(false);
      break;
    case R.id.btn_4:
       btn1.setChecked(false);
       btn2.setChecked(false);
      break;
    

    Hope it helps.