How to un-check radio button without radio group?

Brian J picture Brian J · Jan 11, 2014 · Viewed 9.9k times · Source

I have used the following code snippet to set one radio button to unchecked if the other is selected,but when I run the application and select both radio buttons the code doesn't work as both stay selected.

I'm using a relative layout so I can't use any other solutions with a radio group,I'm just using two seperate radio buttons.

Can someone point out where I could be going wrong somewhere as I can't see a flaw in the logic,any ideas?

Anyways this is the solution I'm trying to implement but its not working in application:

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.radBtnMM:
                if (checked)
                    //set inch button to unchecked
                     radioInch.setChecked(false);
                break;
            case R.id.radBtnInch:
                if (checked)
                    //set MM button to unchecked
                    radioMM.setChecked(false);
                break;
        }
    }

Answer

Miłosz picture Miłosz · Jan 11, 2014

When is Your public void onRadioButtonClicked(View view) called? Is it from a listener?

This will work:

layout.xml:

<RadioButton 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radBtnMM"
/>
<RadioButton 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radBtnInch"
/>

YourActivity.java:

public class MainActivity extends Activity implements OnCheckedChangeListener {
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    setContentView(R.layout.activity_main);
    rb1 = (RadioButton) findViewById(R.id.radBtnInch);
    rb1.setOnCheckedChangeListener(this);
    rb2 = (RadioButton) findViewById(R.id.radBtnMM);
    rb2.setOnCheckedChangeListener(this);
    return true;
  }
  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked) {
      if (buttonView.getId() == R.id.radBtnInch) {
        rb2.setChecked(false);
      }
      if (buttonView.getId() == R.id.radBtnMM) {
        rb1.setChecked(false);
      }
    }
  }