萬盛學電腦網

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

Android RadioGroup 單選按鈕完整實戰:分組管理、事件監聽與動態構建

RadioGroup 與 RadioButton 核心機制

  • RadioGroup:單選容器,管理內部 RadioButton 互斥邏輯 (同組僅一可選)
  • RadioButton:繼承 CompoundButton,可單獨使用但失去互斥特性
  • 核心原理: Group 內 setOnCheckedChangeListener 監聽 checkedId 變化

XML 佈局最佳實踐

<!-- res/layout/activity_radio_demo.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="性別選擇 (單選組 1)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/rg_gender"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:checkedButton="@+id/rb_male">  <!-- 預設選中 -->

        <RadioButton
            android:id="@+id/rb_male"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="男"
            android:buttonTint="@color/primary" />

        <RadioButton
            android:id="@+id/rb_female"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="女"
            android:buttonTint="@color/primary" />

        <RadioButton
            android:id="@+id/rb_other"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="其他"
            android:buttonTint="@color/primary" />
    </RadioGroup>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="?attr/colorOutline"
        android:layout_marginVertical="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="會員等級 (單選組 2 - 垂直)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/rg_level"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/rb_bronze"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="銅牌會員"
            android:paddingVertical="8dp" />

        <RadioButton
            android:id="@+id/rb_silver"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="銀牌會員"
            android:paddingVertical="8dp" />

        <RadioButton
            android:id="@+id/rb_gold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="金牌會員"
            android:paddingVertical="8dp" />
    </RadioGroup>
</LinearLayout>

Activity / Fragment 完整邏輯實現

public class RadioDemoActivity extends AppCompatActivity {

    private RadioGroup rgGender, rgLevel;
    private RadioButton rbMale, rbFemale, rbOther;
    private RadioButton rbBronze, rbSilver, rbGold;
    private TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_demo);
        
        initViews();
        setupListeners();
        // 程式化設置預設選中 (XML checkedButton 也可)
        rbMale.setChecked(true);
        rbBronze.setChecked(true);
    }

    private void initViews() {
        rgGender = findViewById(R.id.rg_gender);
        rgLevel = findViewById(R.id.rg_level);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        rbOther = findViewById(R.id.rb_other);
        rbBronze = findViewById(R.id.rb_bronze);
        rbSilver = findViewById(R.id.rb_silver);
        rbGold = findViewById(R.id.rb_gold);
        tvResult = findViewById(R.id.tv_result);
    }

    private void setupListeners() {
        // 組 1:性別選擇監聽
        rgGender.setOnCheckedChangeListener((group, checkedId) -> {
            String gender = "";
            if (checkedId == R.id.rb_male) gender = "男";
            else if (checkedId == R.id.rb_female) gender = "女";
            else if (checkedId == R.id.rb_other) gender = "其他";
            updateResult("性別: " + gender);
        });

        // 組 2:會員等級監聽
        rgLevel.setOnCheckedChangeListener((group, checkedId) -> {
            String level = "";
            int drawableRes = 0;
            if (checkedId == R.id.rb_bronze) { level = "銅牌"; drawableRes = R.drawable.ic_bronze; }
            else if (checkedId == R.id.rb_silver) { level = "銀牌"; drawableRes = R.drawable.ic_silver; }
            else if (checkedId == R.id.rb_gold) { level = "金牌"; drawableRes = R.drawable.ic_gold; }
            updateResult("等級: " + level);
            // 可動態改圖標等
        });

        // 程式化獲取當前選中 ID
        findViewById(R.id.btn_get_selection).setOnClickListener(v -> {
            int genderId = rgGender.getCheckedRadioButtonId();
            int levelId = rgLevel.getCheckedRadioButtonId();
            String msg = "Gender ID: " + genderId + ", Level ID: " + levelId;
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        });

        // 程式化清除選中 (RadioGroup 無直接 clearCheck 直到 API 29+)
        findViewById(R.id.btn_clear).setOnClickListener(v -> {
            rgGender.clearCheck(); // API 29+ (Android 10)
            rgLevel.clearCheck();
            // 兼容舊版:rgGender.check(-1); 或遍歷子 View setChecked(false)
        });
    }

    private void updateResult(String addition) {
        tvResult.setText("當前選擇: " + addition);
    }
}

進階技巧:動態構建 RadioGroup

public void buildDynamicRadioGroup(List<String> options, LinearLayout container, 
                                   OnCheckedChangeListener listener) {
    RadioGroup radioGroup = new RadioGroup(this);
    radioGroup.setOrientation(LinearLayout.VERTICAL);
    radioGroup.setOnCheckedChangeListener(listener);
    
    RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 16, 0, 16); // dp 轉 px 略
    
    for (int i = 0; i < options.size(); i++) {
        RadioButton rb = new RadioButton(this);
        rb.setId(View.generateViewId()); // API 17+ 唯一 ID
        rb.setText(options.get(i));
        rb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        rb.setPadding(24, 16, 24, 16);
        rb.setButtonTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.primary)));
        radioGroup.addView(rb, lp);
    }
    
    container.addView(radioGroup);
}

// 使用示例
buildDynamicRadioGroup(
    Arrays.asList("選項 A", "選項 B", "選項 C", "選項 D"),
    findViewById(R.id.dynamic_container),
    (group, checkedId) -> {
        RadioButton selected = group.findViewById(checkedId);
        Toast.makeText(this, "動態選擇: " + selected.getText(), Toast.LENGTH_SHORT).show();
    }
);

常見坑點與解決方案

問題 原因 解決
RadioButton 不互斥 未放入同一 RadioGroup、或嵌套 Layout 導致非直屬子 View 確保直接放入 RadioGroup,或手動管理互斥邏輯
setOnCheckedChangeListener 觸發兩次 程式化 setChecked(true) 觸發 + 用戶點擊觸發 用標記位區分,或用 setOnClickListener 代替
clearCheck() 無效 / 崩潰 API < 29 不支援 radioGroup.check(-1); 或 for (int i=0; i<rg.getChildCount(); i++) ((RadioButton)rg.getChildAt(i)).setChecked(false);
獲取選中文字為空 用 rg.getCheckedRadioButtonId() 取 ID 再 findViewById 取文字 RadioButton rb = findViewById(rg.getCheckedRadioButtonId()); String text = rb.getText().toString();
列表項裡用 RadioButton 點擊不觸發 ListView/RecyclerView 項目點擊事件攔截 android:focusable="false" android:focusableInTouchMode="false" 或用 CheckBox 模擬單選

Material Design 3 風格客製化

<!-- res/values/themes.xml -->
<style name="Widget.App.RadioButton" parent="Widget.Material3.CompoundButton.RadioButton">
    <item name="buttonTint">?attr/colorPrimary</item>
    <item name="android:textAppearance">?attr/textAppearanceBodyLarge</item>
    <item name="android:minHeight">48dp</item> <!-- 觸控目標尺寸 -->
    <item name="android:layout_marginVertical">4dp</item>
</style>

<!-- 佈局中引用 -->
<RadioButton style="@style/Widget.App.RadioButton" ... />

架構層面:ViewModel + LiveData/Flow 綁定

// ViewModel
class ProfileViewModel : ViewModel() {
    private val _gender = MutableLiveData<Gender>(Gender.MALE)
    val gender: LiveData<Gender> = _gender
    
    fun setGender(gender: Gender) { _gender.value = gender }
}

// Activity/Fragment (Data Binding 或手動觀察)
viewModel.gender.observe(viewLifecycleOwner) { gender ->
    binding.rgGender.check(gender.radioButtonId) // 映射 Enum -> Res ID
}

binding.rgGender.setOnCheckedChangeListener { _, checkedId ->
    val gender = Gender.fromRadioButtonId(checkedId) ?: return@setOnCheckedChangeListener
    viewModel.setGender(gender)
}

掌握 RadioGroup 的分組機制、事件流向、動態構建與現代架構整合,能讓您構建出穩健、美觀、可維護的單選交互體驗。記住:**單選組必須由 RadioGroup 管理,動態生成用 View.generateViewId(),舊版 API 用 check(-1) 清除選中。**

copyright © 萬盛學電腦網 all rights reserved