Radio Buttons

本文介绍了如何使用RadioButtons组件实现用户从一组选项中进行单一选择的功能。包括如何在布局文件中设置RadioButtons及其所在的RadioGroup,以及如何定义点击事件处理器响应用户的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Radio Buttons 允许用户从一个集合中做出一个选择。如果你觉得用户需要对比每个选择,你可以通过使用radio button来实现,如果不需要的话你可以使用spinner替换


你可以在layout中创建每个radio button。但是,由于radio button都是相互关联的,你必须使用RadioGroup把他们包含起来。通过RadioGroup,系统会限制用户,只能选择一个radio button.

响应点击事件

当用户选择点击了一个radio button, radio button 对象会收到一个点击事件。

你可以在<RadioButton>标签中添加android:onClick属性,来定义处理的点击事件函数handler,这个值是一个函数名称,也就是你要响应回调的点击事件函数。当Activity加载了你的layout的时候,你需要在你的Activity中响应实这个函数。例如

这是一个有两个RadioButton的对象的xml

<?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>

Note:RadioGroup 是LinearLayout 的一个子类,默认是垂直排列

在Activity中,添加radio button 的点击事件响应函数:

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
    
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)
                // Pirates are the best
            break;
        case R.id.radio_ninjas:
            if (checked)
                // Ninjas rule
            break;
    }
}

你定义的这个函数,必须要按照下面的定义去实现:

1.必须是public的方法

2.返回是void

3.参数只能是View,而且只能是一个(View 其实就是你点击的对象)

Tip:你可以通过使用setChecked(boolean) 或者 toggle() 来改变radio button 的状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值