Turn the Radio Up

As with other implementations of radio buttons in other toolkits, Android's radio buttons are two-state, like checkboxes, but can be grouped such that only one radio button in the group can be checked at any time.

Like CheckBox, RadioButton inherits from CompoundButton, which in turn inherits from TextView. Hence, all the standard TextView properties for font face, style, color, etc., are available for controlling the look of radio buttons. Similarly, you can call isChecked() on a RadioButton to see if it is selected, toggle() to select it, and so on, like you can with a CheckBox.

Most times, you will want to put your RadioButton widgets inside of a RadioGroup. The RadioGroup indicates a set of radio buttons whose state is tied, meaning only one button out of the group can be selected at any time. If you assign an android:id to your RadioGroup in your XML layout, you can access the group from your Java code and invoke:

• check() to check a specific radio button via its ID (e.g., group.check(R.id.radio1))

• clearCheck() to clear all radio buttons, so none in the group are checked

• getCheckedRadioButtonId() to get the ID of the currently-checked radio button (or -1 if none are checked)

For example, from the Basic/RadioButton sample application, here is an XML layout showing a RadioGroup wrapping a set of RadioButton widgets:

<?xml version="1.0" encoding="utf-8"?> <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout width="fill parent"

android:layout height="fill parent" >

<RadioButton android:id="@+id/radio1" android:layout width="wrap content" android:layout height="wrap content" android:text="Rock" />

<RadioButton android:id="@+id/radio2" android:layout width="wrap content" android:layout height="wrap content" android:text="Scissors" />

<RadioButton android:id="@+id/radio3" android:layout width="wrap content" android:layout height="wrap content" android:text="Paper" /> </RadioGroup>

Figure 6-6 shows the result using the stock Android-generated Java for the project and this layout.

Figure 6-6. The RadioButtonDemo sample application

Note that the radio button group is initially set to be completely unchecked at the outset. To pre-set one of the radio buttons to be checked, use either setChecked() on the RadioButton or check() on the RadioGroup from within your onCreate() callback in your activity.

Was this article helpful?

0 0

Post a comment