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;
}
}
To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true .
RadioGroup is just a helper wrapper around RadioButton s to give you some capabilities like if you select a RadioButton, all other RadioButton s in that group will automatically be deselected. If you do without RadioGroup then you have to implement those functionalities yourself.
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);
}
}
}
Try this...
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.radioBtnMM:
// set inch button to unchecked
radioBtnInch.setChecked(!checked);
break;
case R.id.radioBtnInch:
// set MM button to unchecked
radioBtnMM.setChecked(!checked);
break;
}
}
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