Recipe 2.4 Using CheckBoxes

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

Like radio buttons, checkboxes enable users to select one or more options from a list. A CheckBox has two states: checked or unchecked. Unlike radio buttons, checkboxes can be checked and unchecked by the user without regard to the state of other checkboxes. This recipe shows how to use checkboxes in your Android application.

Solution

Assume you have the following code snippet in the 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" >

    <CheckBox
        android:id="@+id/chkAutosave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Autosave" />

    <CheckBox
        android:id="@+id/star"
        style="?android:attr/starStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The CheckBox element defines an item for users to check or uncheck. Android supports a special type of checkbox known as the star checkbox. You display a star checkbox by setting the style attribute and setting its value to ?android:attr/starStyle.

Figure 2-7 shows the default checkbox and the star checkbox. The top part shows the unchecked state of the two checkboxes, and the lower portion shows the checked state.

The following code snippet ...

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.