Recipe 2.3 Using Radio Buttons

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
RadioButtons.zip

Radio buttons enable users to select one item from a list of available options. This recipe shows how to use radio buttons in your Android application.

Solution

Assume you have the following code snippet in your activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/rdbGp1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RadioButton
            android:id="@+id/rdb1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_launcher"
            android:text="Option 1" />

        <RadioButton
            android:id="@+id/rdb2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_launcher"
            android:text="Option 2" 
            android:checked="true"/>
    </RadioGroup>

</LinearLayout>

The RadioButton element represents a two-state button that can be either checked or unchecked. Once a radio button is checked, it cannot be unchecked by tapping on it. Instead, radio buttons are contained within a RadioGroup element, which contains a set of radio buttons. Checking one radio button in a radio group unchecks the rest of the radio buttons in the same group. ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.