单选按钮
单选按钮允许用户从一组选项中选择其中某个选项。如果你认为有必要让用户并排看到所有可选项,并且对这组可选项来说只能有一个被选中,那么单选按钮将是个不错的选择。如果没有必要并排显示所有的选项,那么可以使用 spinner 来代替。
在你的布局中通过创建 RadioButton 标签来创建单选按钮选项。然而,由于单选按钮之间是互斥的,所以你必须把他们集合到一个 RadioGroup 内。这样系统会确保同一时间仅有一个单选按钮会被选中。
响应点击事件
当用户选中其中一个单选按钮后,相应的 RadioButton 对象会收到on-click事件。
在XML布局文件中的<RadioButton>元素中添加 android:onClick 属性就可以为单选按钮定义点击事件处理程序了。这个属性的值必须是你调用来响应点击事件的方法名。使用这个布局的 Activity 必须实现相应的方法。
例如,这里有一对 RadioButton
对象:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
注解: RadioGroup
是 LinearLayout
的一种子类,因此默认情况下它拥有垂直方向的布局属性。
在使用这个布局的 Activity
里,下面的方法会为两个单选按钮处理点击事件:
public void onRadioButtonClicked(View view) {
// 这个按钮现在是否被选中?
boolean checked = ((RadioButton) view).isChecked();
// 检查哪个单选按钮被点击过
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// 海盗是最优秀的
break;
case R.id.radio_ninjas:
if (checked)
// 忍者是最优秀的
break;
}
}
你在 android:onClick 属性中声明的方法名必须和上面显示的一样,而且这个方法必须是:
小贴士:如果你需要自己改变单选按钮状态(比如加载一个保存过的 CheckBoxPreference),那么你可以使用 setChecked(boolean)
或 toggle()
方法达到目的。