RadioButton(单选框)允许用户从多个选项中选择一个,如果在选择的时候需要用户看到所有的选项,那么我们要使用RadioButton, 如果不需要, 那么我们应该使用一个spinner(下拉框). 单选框长这样:
我们可以通过在layout文件中声明<RadioButton>
标签来添加一个RadioButton,然而因为RadioButton是互相排斥的, 每组中只能选择一个, 所以我们必须将它们分组, 分组需要使用<RadioGroup>
标签.
当用户点击RadioButton的时候,RadioButton对象会收到一个点击事件,像Button和CheckBox一样,我们也可以使用android:onClick属性来指定一个方法来响应RadioButton的点击事件, 栗子:
在layout文件中声明RadioGroup和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) {
// 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;
}
}
跟Button和CheckBox的处理方法一样, 这些方法需要满足:
必须是public方法
必须返回void
必须有且仅有一个View参数.
如果我们需要在代码中改变RadioButton本身的状态, 可以使用setChecked(boolean)或者toggle()方法.