本文共 1232 字,大约阅读时间需要 4 分钟。
Radio buttons 只运行用户选择一个选项,一般都是在RadioGroup中放置一组Radio buttons 如下所示: <?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> 上面这两个RadioButton的回调函数都是android:onClick="onRadioButtonClicked。我们可以在activity中根据android:id="@+id/radio_ninjas"来判断是哪个RadioButton 被选中了。 如下所示: 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; } } 和checkbox 一样RadioButton也是CompoundButton.java的子类,可以调用setChecked(boolean)和 toggle() 来改变RadioButton的状态.转载地址:http://gvcmi.baihongyu.com/