Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the selected index of a RadioGroup in Android

People also ask

How do you check whether a RadioGroup is checked or not?

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.

How do I get the radio button value in Kotlin?

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.

How do you programmatically determine whether a radioButton is checked?

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.

How do you use radio groups?

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());