How to check if a radiobutton is checked in a radiogroup in Android?
If you want to check on just one RadioButton
you can use the isChecked
function
if(radioButton.isChecked())
{
// is checked
}
else
{
// not checked
}
and if you have a RadioGroup
you can use
if (radioGroup.getCheckedRadioButtonId() == -1)
{
// no radio buttons are checked
}
else
{
// one of the radio buttons is checked
}
rgrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i) {
case R.id.type_car:
num=1;
Toast.makeText(getApplicationContext()," Car",Toast.LENGTH_LONG).show();
break;
case R.id.type_bike:
num=2;
Toast.makeText(getApplicationContext()," Bike",Toast.LENGTH_LONG).show();
break;
}
}
});
Use the isChecked() function for every radioButton you have to check.
RadioButton maleRadioButton, femaleRadioButton;
maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);
Then use the result for your if/else case consideration.
if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
Log.d("QAOD", "Gender is Selected");
} else {
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
Log.d("QAOD", "Gender is Null");
}
All you need to do is use getCheckedRadioButtonId()
and isChecked()
method,
if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}
https://developer.android.com/guide/topics/ui/controls/radiobutton.html