Android UI How to - Select a RadioButton








The radio buttons within the radio group are, by default, unchecked. You can set one to checked in the XML definition.

To set one of the radio buttons to the checked state programmatically, you can obtain a reference to the radio button and call setChecked():

RadioButton steakBtn = (RadioButton)this.findViewById(R.id.stkRBtn); steakBtn.setChecked(true);

You can also use the toggle() method to toggle the state of the radio button.

XML Example

Select a RadioButton in XML.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from w ww.  j  a  va2  s  . c  o m
    <RadioGroup
        android:id="@+id/rBtnGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chicken" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Fish" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Steak" />

    </RadioGroup>

</LinearLayout>




Java Example

Select a RadioButton in Java code.

package com.java2s.app;
/* ww  w  .  ja  v  a2  s .com*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RadioButton steakBtn = (RadioButton) this.findViewById(R.id.stkRBtn);
        steakBtn.setChecked(true);
    }

}
null