Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadioGroup: How to check programmatically

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?

like image 528
Bao Le Avatar asked Oct 12 '11 16:10

Bao Le


People also ask

How to check radio button programmatically?

In case, if we want to change the state of RadioButton to ON (Checked), then we need to set android:checked = “true” in our XML layout file. In android, we can create RadioButton control in two ways either in the XML layout file or create it in the Activity file programmatically.

Which of the following is the method of the checkable interface to check the state of a radio button?

here you go. Use getCheckedRadioButtonId() method on your RadioGroup to find out.


1 Answers

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

like image 124
Blackbelt Avatar answered Oct 22 '22 03:10

Blackbelt