Radio Button

Two mutually-exclusive radio buttons—enabling one disables the other. When each is pressed, we'll pop up a message. 1. Open the layout file and, inside the LinearLayout, add two RadioButtons, inside a RadioGroup:

<RadioGroup android:layout width="fill parent" android:layout height="wrap content" android:orientation="vertical"> <RadioButton android:id="@+id/radio red" android:layout width="wrap content"

android:layout height="wrap content" android:text="Red" /> <RadioButton android:id="@+id/radio blue" android:layout width="wrap content" android:layout height="wrap content" android:text="Blue" /> </RadioGroup>

2. To do something when each is selected, we'll need an OnClickListener. Unlike the other listeners we've created, instead of creating this one as an anonymous inner class, we'll create it as a new object. This way, we can re-use the OnClickLIstener for both RadioButtons. So, add the following code in the HelloFormStuff Activity (outside the onCreate () method):

OnClickListener radio listener = new OnClickListener() { public void onClick(View v) {

// Perform action on clicks RadioButton rb = (RadioButton) v;

Toast.makeText(HelloFormStuff.this, rb.getText(),

Our onClick () method will be handed the View clicked, so the first thing to do is cast it into a RadioButton. Then we pop up a Toast message that displays the selection.

3. Now, at the bottom of the onCreate() method, add the following:

final RadioButton radio red = (RadioButton) findViewById(R.id.radio red); final RadioButton radio blue = (RadioButton) findViewById(R.id.radio blue); radio red.setOnClickListener(radio listener); radio blue.setOnClickListener(radio listener);

This captures each of the RadioButtons from our layout and adds the newly-created OnClickListener to each.

Tip: If you find that you need to change the state of a RadioButton in another way (such as when loading a saved CheckBoxPreference), use setChecked(true) or toggle() .

0 0

Post a comment