iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

我們將介紹另外兩個常見的 Android 元件:CheckBox 和 RadioButton。這兩者經常出現在涉及選擇的應用場景中,儘管它們在功能和外觀上有所相似,但用途和適用的情境卻有所不同。

1. CheckBox:多選功能的好幫手

CheckBox 的基本用法

CheckBox 是一個可以讓用戶多選的元件,用戶可以一次選擇多個選項。它適合用於那些不要求用戶只能選擇一個選項的情況,例如愛好選擇、偏好設定等。

XML 定義 CheckBox:

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="選項 A" />

獲取 CheckBox 的狀態

我們可以通過程式碼來檢查 CheckBox 是否被選中:

CheckBox checkBox = findViewById(R.id.checkbox);
boolean isChecked = checkBox.isChecked();

設定 CheckBox 的狀態變化監聽

可以為 CheckBox 設定一個 OnCheckedChangeListener 來監聽使用者是否選擇或取消選擇該選項:

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // 選中了此選項所執行的動作
        } else {
            // 取消選擇了此選項所執行的動作
        }
    }
});

2. RadioButton:單選功能的專家

RadioButton 的基本用法

RadioButton 通常與 RadioGroup 一起使用,它是一個用於單選的元件,用戶只能在一組選項中選擇一個。這在性別選擇、支付方式選擇等場景中非常常見。

XML 定義 RadioButton 與 RadioGroup:

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="選項 A" />
    
    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="選項 B" />
</RadioGroup>

獲取 RadioButton 的選擇狀態

可以通過 RadioGroup 來檢查用戶選擇了哪一個選項:

RadioGroup radioGroup = findViewById(R.id.radioGroup);
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton selectedRadioButton = findViewById(selectedId);
String selectedText = selectedRadioButton.getText().toString();

設定 RadioButton 的選擇監聽

我們可以使用 OnCheckedChangeListener 來監聽 RadioButton 的選擇變化:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton radioButton = findViewById(checkedId);
        // 根據選擇的 RadioButton 進行處理
    }
});

3. 總結

在今天的文章中,我們介紹了 CheckBox 和 RadioButton 的基本使用和配置。這兩個元件都是用於選擇操作的好工具,通過詳細理解和靈活運用它們,可以讓應用的交互性更上一層樓。
明天我們將繼續介紹更多 Android 開發中的常用元件,敬請期待!


上一篇
# DAY08 掌握 Button 和 ImageView 的使用技巧
下一篇
# Day 10 探索 Android 中的常用元件之 SeekBar 與 ProgressBar
系列文
「淺入 Android Studio 開發環境」—— 工具與插件的高效使用29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言