首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android RadioButton 跨 RadioGroup 互斥:自定義 MutilRadioGroup 徹底解決

     編輯:程式設計綜合問答

痛點

複雜佈局導致 RadioButton 分散在不同容器,無法放入同一 RadioGroup,原生互斥失效。

方案:繼承 LinearLayout 實現 MutilRadioGroup

核心邏輯:

  1. 掃描所有子孫 View,收集 RadioButton。
  2. 為每個 RadioButton 動態設置 OnCheckedChangeListener。
  3. 選中時遍歷其餘按鈕 setChecked(false),並通過 mProtectFromCheckedChange 防遞歸。
  4. 支持 View.NO_ID 自動生成 ID(API 17+)。

關鍵代碼片段

public class MutilRadioGroup extends LinearLayout {
    private int mCheckedId = -1;
    private final CheckedStateTracker mChildListener = new CheckedStateTracker();

    @Override public void addView(View child, int index, LayoutParams params) {
        List btns = getAllRadioButton(child);
        if (btns != null) {
            for (RadioButton btn : btns) {
                if (btn.isChecked()) setCheckedId(btn.getId()); // 同步初始狀態
                btn.setOnCheckedChangeListener(mChildListener);
            }
        }
        super.addView(child, index, params);
    }

    private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (mProtectFromCheckedChange) return;
            mProtectFromCheckedChange = true;
            if (mCheckedId != -1) setCheckedStateForView(mCheckedId, false);
            mProtectFromCheckedChange = false;
            setCheckedId(buttonView.getId());
        }
    }
    // ... 完整代碼見原文,含 ID 自動生成、狀態持久化、無障礙支持
}

使用方式

<com.xhbok.shundai.view.MutilRadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RadioButton android:id="@+id/rb1" ... />
    <LinearLayout ...>
        <RadioButton android:id="@+id/rb2" ... />
    </LinearLayout>
    <RadioButton android:id="@+id/rb3" ... />
</com.xhbok.shundai.view.MutilRadioGroup>

優勢

  • 零侵入:不改動現有佈局結構。
  • 全自動:動態添加/移除 RadioButton 自動生效。
  • 兼容性:支持嵌套任意 ViewGroup、API 17+ 自動分配 ID。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved