here you go. Use getCheckedRadioButtonId() method on your RadioGroup to find out. It returns -1 when no RadioButton in the group is selected. You are already doing this.
This example demonstrates how to use Radio Button in Android Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
You can check the current state of a radio button programmatically by using isChecked() method. This method returns a Boolean value either true or false. if it is checked then returns true otherwise returns false.
A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio group, it automatically unchecks any previously checked radio button within the same group.
You should be able to do something like this:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup
contains other Views (like a TextView
) then the indexOfChild()
method will return wrong index.
To get the selected RadioButton
text on the RadioGroup
:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();
This should work,
int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
You could have a reference to the radio group and use getCheckedRadioButtonId ()
to get the checked radio button id. Take a look here
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);
Then when you need to get the selected radio option.
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
// No item selected
}
else{
if (checkedRadioButtonId == R.id.radio_button1) {
// Do something with the button
}
}
try this
RadioGroup group= (RadioGroup) getView().findViewById(R.id.radioGroup);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
View radioButton = radioGroup.findViewById(i);
int index = radioGroup.indexOfChild(radioButton);
}
});
You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()
You can use:
RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
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