RadioGroup: How to check programmatically
Asked Answered
F

12

72

I create a RadioGroup from XML

    <RadioGroup android:id="@+id/option" 
        android:layout_width="match_parent"
        android:orientation="horizontal" 
        android:checkedButton="@+id/block_scenario_off"
        android:layout_height="wrap_content">
        <RadioButton 
            android:layout_width="0dip"
            android:layout_weight="1" 
            android:text="@string/option1" 
            android:layout_height="wrap_content" 
            android:id="@+id/option1"
            android:layout_gravity="center|left" 
            android:onClick="@string/on_click"/>
        <RadioButton 
            android:layout_width="0dip"
            android:layout_weight="1" 
            android:text="@string/option2" 
            android:onClick="@string/on_click"
            android:layout_height="wrap_content"
            android:layout_gravity="center" 
            android:id="@+id/option2"/>
        <RadioButton 
            android:layout_width="0dip"
            android:layout_weight="1" 
            android:text="@string/option3"
            android:onClick="@string/on_click" 
            android:layout_height="wrap_content"
            android:layout_gravity="center|right" 
            android:id="@+id/option3" />
    </RadioGroup>

In Java code, I programmatically check the first one on activity creation (onCreate()) as following:

    mOption = (RadioGroup) findViewById(R.id.option);
    mOption.check(R.id.option1);

But when the activity is shown, no radio button is checked. Any help?

Furze answered 12/10, 2011 at 16:18 Comment(1)
If you wanted to check the radio buttons programmatically then you should not have accepted that answer because that is how we set them checked on the xml file!Breeding
B
87

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(R.id.option1); b.setChecked(true);

Baluster answered 12/10, 2011 at 16:30 Comment(13)
Try to add that option to both RadioGroup and/or RadioButton levels, does not workFurze
you have to add this option ONLY to RadioButton checked by defaultBaluster
Yes, it works for the RadioButton with checked attribute assigned in XML, but it does not work with Java code (i.e. mOption.check(R.id.option1));Furze
Since I have two RadioGroup in the same layout, the code does not work. If I remove one, the other works well. I have still the problem with two or more RadioGroup in the same layout. ThanksFurze
This is NOT what "programmatically" means.Chaperon
This answer is wrong and dangerous. setting a radiobutton checked will not modify the state of the RadioGroup. Bao Le is saying himself why he wasn't able to make it work: he had the same id repeated twice inside the xml.Diverticulitis
@Diverticulitis would you mind explaining what's dangerous and wrong in this answer ?Baluster
@Baluster the fact that you see the radiobutton set (after you called setChecked), but the state of the RadioGroup is not changed inside. This could lead to subtle bugs where you see a radiobutton set visually but you query the state of the RadioGroup and you get the id of another radiobutton set.Diverticulitis
@Baluster i just had a bug where i setChecked(false) a radiobutton, so the RadioGroup was all unchecked, and clicking on the same option didn't turn the radiobutton on (because for the radiogroup it was already on). So wrong is the fact that doesn't change the RadioGroup state, which is the object that should manage the state. Dangerous is cause it leads to subtle bugs.Diverticulitis
@AndrewBloom, it is not a subtle bug. It is the expected behavior as per RadioGroup documentation.Baluster
@Blackbelt, it's difficult to explain to a user that sees no options set on a radiogroup but he can't set one on of them clicking on it, that is 'the expected behaviour as per RadioGroup documentation' though.Diverticulitis
Thanks bro, this helped me so much!Nominee
Downvoted because this answer doesn't actually result in expected behaviour: to wit, that the radiobutton will behave as if selected by the user; and other radiobuttons in the group will become deselected. Nobody uses a single radiobutton in isolation, so this answer is at best useless and at worst harmful.Covenant
T
41

try this if you want your radio button to be checked based on value of some variable e.g. "genderStr" then you can use following code snippet

    if(genderStr.equals("Male"))
       genderRG.check(R.id.maleRB);
    else 
       genderRG.check(R.id.femaleRB);
Tarsuss answered 21/2, 2012 at 13:41 Comment(0)
F
32

I use this code piece while working with indexes for radio group:

radioGroup.check(radioGroup.getChildAt(index).getId());
Foresaid answered 18/7, 2017 at 10:49 Comment(2)
Best answer. One line. Easy to understand. Single Object required. Can be added to a method very easily.Equality
This should be at top. Others are unnecessarily complicated.Bacciform
D
30

Watch out! checking the radiobutton with setChecked() is not changing the state inside the RadioGroup. For example this method from the radioGroup will return a wrong result: getCheckedRadioButtonId().

Check the radioGroup always with

mOption.check(R.id.option1);

you've been warned ;)

Diverticulitis answered 8/5, 2016 at 13:55 Comment(0)
E
27

You may need to declare the radio buttons in the onCreate method of your code and use them.

RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(true);
Epitaph answered 12/10, 2011 at 19:58 Comment(1)
This isn't working for me, nor mOption.check(R.id.option1); I have tried in onCreate() and onResume(). What is wrong?Chaperon
F
14

Also you can use getChildAt() method. Like this:

mOption = (RadioGroup) findViewById(R.id.option);
((RadioButton)mOption.getChildAt(0)).setChecked(true);
Fray answered 29/1, 2016 at 9:32 Comment(0)
M
13

Grab the radio group and look at the children to see if any are unchecked.

RadioGroup rg = (RadioGroup) view;
int checked = savedInstanceState.getInt(wrap.getAttributeName());

if(checked != -1) {
    RadioButton btn = (RadioButton) rg.getChildAt(checked);
    btn.toggle();
}
Macaulay answered 30/7, 2012 at 12:11 Comment(1)
I think checked must be >-1 not !=-1Blowing
C
13

I use this code piece while working with getId() for radio group:

radiogroup.check(radiogroup.getChildAt(0).getId());

set position as per your design of RadioGroup

hope this will help you!

Cafard answered 18/8, 2018 at 8:26 Comment(0)
L
8

it will work if you put your mOption.check(R.id.option1); into onAttachedToWindow method or like this:

view.post(new Runnable()
{
    public void run() 
    {
        // TODO Auto-generated method stub
        mOption.check(R.id.option1); 
    }
});

the reason may be that check method will only work when the radiogroup is actually rendered.

Laski answered 6/9, 2012 at 8:58 Comment(1)
david's comment in his answer that the check method would not work until the radiogroup was actually rendered turned out to solve a mystery for me.Ocieock
C
5

In Kotlin. Select first element. And you need to do this in onViewCreated or later.

radioGroup.apply { check(getChildAt(0).id) }
Conflagrant answered 24/5, 2021 at 16:29 Comment(0)
K
2

I prefer to use

RadioButton b = (RadioButton) findViewById(R.id.option1);
b.performClick();

instead of using the accepted answer.

RadioButton b = (RadioButton) findViewById(R.id.option1);
b.setChecked(true);

The reason is setChecked(true) only changes the checked state of radio button. It does not trigger the onClick() method added to your radio button. Sometimes this might waste your time to debug why the action related to onClick() not working.

Khania answered 9/1, 2020 at 23:13 Comment(0)
K
0

For Kotlin:

check(radioGroup.children.first().id)

Krems answered 16/6, 2022 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.