Radio Buttons(单选按钮)

单选按钮

单选按钮允许用户从一组选项中选择其中某个选项。如果你认为有必要让用户并排看到所有可选项,并且对这组可选项来说只能有一个被选中,那么单选按钮将是个不错的选择。如果没有必要并排显示所有的选项,那么可以使用 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 属性中声明的方法名必须和上面显示的一样,而且这个方法必须是:

  • 公共的
  • 返回void
  • 定义一个 View 作为它唯一的参数(它会作为被点击的 View) 

小贴士:如果你需要自己改变单选按钮状态(比如加载一个保存过的 CheckBoxPreference),那么你可以使用 setChecked(boolean) 或 toggle() 方法达到目的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值