Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android CheckBox 與 RadioButton 控制項用法

編輯:關於 Android 程式設計

控制項差異

CheckBox 與 RadioButton 都只有選取與未選取狀態。CheckBox 可多選,RadioButton 則需放入 RadioGroup 中,同一時間只能有一個選項被選取。

版面配置

<RadioGroup android:id="@+id/radioGroup" android:orientation="horizontal"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <RadioButton android:id="@+id/on" android:text="開燈" android:checked="true" />
    <RadioButton android:id="@+id/off" android:text="關燈" />
</RadioGroup>

<CheckBox android:id="@+id/checkBox" android:text="開燈"
    android:checked="true" android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

事件處理

OnCheckedChangeListener listener = new OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView instanceof RadioButton) {
            imageView01.setImageResource(isChecked ? R.drawable.bulb_on : R.drawable.bulb_off);
        } else if (buttonView instanceof CheckBox) {
            checkBox.setText(isChecked ? "開燈" : "關燈");
            imageView02.setImageResource(isChecked ? R.drawable.bulb_on : R.drawable.bulb_off);
        }
    }
};
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved