Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...