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 的状态