Android Tutorial

(avery) #1

By : Ketan Bhimani


186 

<RadioButton
android:id=”@+id/RadioButton04”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Option 4”>



You handle actions on these RadioButton objects through the
RadioGroup object.The following example shows registering for
clicks on the RadioButton objects within the RadioGroup:

final RadioGroup group = (RadioGroup)findViewById(R.id.RadioGroup01);
final TextView tv = (TextView)findViewById(R.id.TextView01);
group.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(
RadioGroup group, int checkedId) {
if (checkedId != -1) {
RadioButton rb = (RadioButton)findViewById(checkedId);
if (rb != null) {
tv.setText(“You chose: “ + rb.getText());
}
} else {
tv.setText(“Choose 1”);
}
}
});


As this layout example demonstrates, there is nothing special that
you need to do to make the RadioGroup and internal RadioButton
objects work properly.The preceding code illustrates how to register
to receive a notification whenever the RadioButton selection
changes.

The code demonstrates that the notification contains the resource
identifier for the specific RadioButton that the user chose, as
assigned in the layout file. To do something interesting with this,
you need to provide a mapping between this resource identifier (or
the text label) to the corresponding functionality in your code. In
the example, we query for the button that was selected, get its
Free download pdf