Select a RadioButton

Description

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 w  w  .j ava 2 s . c  om
    <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;
/*w  w w  .java2s. 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);
    }

}
Select a RadioButton




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView