原
单选按钮允许用户从一组中选择一个选项。如果您认为用户需要并排查看所有可用选项,则应使用单选按钮的单选按钮。如果没有必要并排显示所有选项,请使用微调器。
要创建每个单选按钮选项,请RadioButton在布局中创建一个。但是,因为单选按钮是互斥的,所以必须将它们组合在一起 RadioGroup。通过将它们组合在一起,系统确保一次只能选择一个单选按钮。
关键类如下:
RadioButton
RadioGroup
响应Click事件
当用户选择其中一个单选按钮时,相应的RadioButton对象接收点击事件。
要为按钮定义单击事件处理程序,请将该android:onClick属性添加到<RadioButton>XML布局中的 元素。此属性的值必须是您要响应click事件时要调用的方法的名称。然后Activity托管布局必须实现相应的方法。
例如,以下是几个RadioButton对象:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_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托管此布局的内部,以下方法处理两个单选按钮的click事件:
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;
}
}
您在android:onClick属性中声明的方法必须具有完全如上所示的签名。具体来说,该方法必须:
公开
返回无效
将a定义View为唯一参数(这将View是单击的参数)
提示:如果您需要自己更改单选按钮状态(例如加载已保存的状态CheckBoxPreference),请使用setChecked(boolean)或toggle()方法。
联系我
QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ
公众号推荐: