複雜佈局導致 RadioButton 分散在不同容器,無法放入同一 RadioGroup,原生互斥失效。
核心邏輯:
RadioButton。OnCheckedChangeListener。setChecked(false),並通過 mProtectFromCheckedChange 防遞歸。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>