| 元件 | 選擇模式 | 典型用途 |
|---|---|---|
| RadioButton + RadioGroup | 單選(互斥) | 性別、付款方式 |
| CheckBox | 多選(獨立) | 興趣、同意條款 |
<RadioGroup android:id="@+id/myRadioGroup"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton android:id="@+id/myRadioButton1" android:text="女" />
<RadioButton android:id="@+id/myRadioButton2" android:text="男" />
</RadioGroup>
<CheckBox android:id="@+id/swim" android:text="游泳" />
<CheckBox android:id="@+id/run" android:text="跑步" />
<CheckBox android:id="@+id/read" android:text="閱讀" />
public class OptionActivity extends Activity {
RadioGroup rg; RadioButton rbFemale, rbMale;
CheckBox cbSwim, cbRun, cbRead;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rg = findViewById(R.id.myRadioGroup);
rbFemale = findViewById(R.id.myRadioButton1);
rbMale = findViewById(R.id.myRadioButton2);
cbSwim = findViewById(R.id.swim);
cbRun = findViewById(R.id.run);
cbRead = findViewById(R.id.read);
// RadioGroup 統一監聽
rg.setOnCheckedChangeListener((group, checkedId) -> {
if (checkedId == rbFemale.getId()) toast("選擇:女");
else if (checkedId == rbMale.getId()) toast("選擇:男");
});
// CheckBox 各自監聽
CompoundButton.OnCheckedChangeListener cbListener = (btn, checked) -> {
String txt = btn.getText().toString();
toast((checked ? "勾選:" : "取消:") + txt);
};
cbSwim.setOnCheckedChangeListener(cbListener);
cbRun.setOnCheckedChangeListener(cbListener);
cbRead.setOnCheckedChangeListener(cbListener);
}
void toast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); }
}
android:checkedButton 預設選中。android:button@null + android:drawableLeft 自訂圖示。RadioGroup.addView() / removeView()。RadioGroup 處理互斥單選,CheckBox 處理獨立多選,善用統一監聽器減少樣板碼。