萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 選項組件完整教學:RadioGroup 單選與 CheckBox 多選事件處理

元件對比

元件選擇模式典型用途
RadioButton + RadioGroup單選(互斥)性別、付款方式
CheckBox多選(獨立)興趣、同意條款

版面 (main.xml)

<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="閱讀" />

Activity 事件處理

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(); }
}

進階技巧

  • RadioGroup android:checkedButton 預設選中。
  • CheckBox 文字過長可用 android:button@null + android:drawableLeft 自訂圖示。
  • 動態增減選項時,操作 RadioGroup.addView() / removeView()。

總結

RadioGroup 處理互斥單選,CheckBox 處理獨立多選,善用統一監聽器減少樣板碼。

copyright © 萬盛學電腦網 all rights reserved