RadioGroup 配合 RadioButton 實現互斥單選,是表單、設置、問卷、篩選器的核心組件。本文提供完整的 **資源分離 (strings.xml) + 佈局聲明 (main.xml) + 邏輯控制 (Java/Kotlin)** 三層架構代碼,詳解 OnCheckedChangeListener 監聽、動態增減選項、預設選中、禁用狀態、自定義樣式、按鈕模式 (無圓點) 等進階用法。
res/values/strings.xml (國際化基石)<resources>
<string name="app_name">RadioGroup Demo</string>
<string name="question_gender">請選擇您的性別:</string>
<string name="option_male">男生</string>
<string name="option_female">女生</string>
<string name="option_other">其他</string>
<string name="toast_selected">您選擇了:%s</string>
<string name="toast_none">請先選擇一項</string>
</resources>
res/layout/activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<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="24dp"
android:gravity="center_vertical">
<!-- 提示文本 -->
<TextView
android:id="@+id/tv_question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/question_gender"
android:textSize="20sp"
android:textColor="#212121"
android:layout_marginBottom="16dp" />
<!-- RadioGroup 容器:垂直排列,單選互斥 -->
<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/rb_male" <!-- XML 預設選中 (API 23+ 支持引用 ID) -->
android:layout_gravity="center_horizontal">
<RadioButton
android:id="@+id/rb_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/option_male"
android:textSize="16sp"
android:textColor="#333333"
android:buttonTint="#2196F3" <!-- 圓點顏色 (API 21+) -->
android:paddingVertical="8dp" />
<RadioButton
android:id="@+id/rb_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/option_female"
android:textSize="16sp"
android:textColor="#333333"
android:buttonTint="#2196F3"
android:paddingVertical="8dp" />
<RadioButton
android:id="@+id/rb_other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/option_other"
android:textSize="16sp"
android:textColor="#333333"
android:buttonTint="#2196F3"
android:paddingVertical="8dp" />
</RadioGroup>
<!-- 操作按鈕 -->
<Button
android:id="@+id/btn_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="提交"
android:backgroundTint="#2196F3"
android:textColor="#FFFFFF" />
</LinearLayout>
MainActivity.javapublic class MainActivity extends AppCompatActivity {
private RadioGroup rgGender;
private RadioButton rbMale, rbFemale, rbOther;
private Button btnSubmit;
private TextView tvQuestion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 綁定視圖
rgGender = findViewById(R.id.rg_gender);
rbMale = findViewById(R.id.rb_male);
rbFemale = findViewById(R.id.rb_female);
rbOther = findViewById(R.id.rb_other);
btnSubmit = findViewById(R.id.btn_submit);
tvQuestion = findViewById(R.id.tv_question);
// 2. 設置選中變化監聽器 (核心)
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
// checkedId 為被選中的 RadioButton 的 ID,未選中時為 -1
String selectedText = "";
if (checkedId == R.id.rb_male) {
selectedText = getString(R.string.option_male);
} else if (checkedId == R.id.rb_female) {
selectedText = getString(R.string.option_female);
} else if (checkedId == R.id.rb_other) {
selectedText = getString(R.string.option_other);
}
// 實時反饋 (可選)
if (!selectedText.isEmpty()) {
tvQuestion.setText(getString(R.string.toast_selected, selectedText));
}
}
});
// 3. 提交按鈕點擊:獲取當前選中值
btnSubmit.setOnClickListener(v -> {
int checkedId = rgGender.getCheckedRadioButtonId();
if (checkedId != -1) {
RadioButton selectedRb = findViewById(checkedId);
String text = selectedRb.getText().toString();
Toast.makeText(this, getString(R.string.toast_selected, text), Toast.LENGTH_SHORT).show();
// 提交業務邏輯...
} else {
Toast.makeText(this, R.string.toast_none, Toast.LENGTH_SHORT).show();
}
});
// 4. 程式化操作示例
// rgGender.check(R.id.rb_female); // 程式化選中
// rgGender.clearCheck(); // 清除選中 (無選中狀態)
// rbOther.setEnabled(false); // 禁用某項
// rbOther.setVisibility(View.GONE); // 隱藏某項 (動態增減)
// rgGender.setOrientation(LinearLayout.HORIZONTAL); // 動態改橫向
}
}
<RadioButton
...
android:button="@null" <!-- 隱藏默認圓點 -->
android:background="@drawable/btn_radio_selector" <!-- 狀態選擇器背景 -->
android:padding="12dp 24dp" />
<!-- res/drawable/btn_radio_selector.xml -->
<selector xmlns:android="...">
<item android:state_checked="true" android:drawable="@drawable/bg_selected_blue" />
<item android:drawable="@drawable/bg_unselected_gray" />
</selector>
適用於標籤頁、篩選器、段落選擇器等場景。
// 添加
RadioButton newRb = new RadioButton(this);
newRb.setId(View.generateViewId()); // API 17+ 生成唯一 ID
newRb.setText("新選項");
newRb.setLayoutParams(new RadioGroup.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
rgGender.addView(newRb);
// 移除
rgGender.removeView(rbOther); // 或 rgGender.removeViewAt(index)
int index = rgGender.indexOfChild(findViewById(rgGender.getCheckedRadioButtonId()));
// 或遍歷
for (int i = 0; i < rgGender.getChildCount(); i++) {
if (((RadioButton) rgGender.getChildAt(i)).isChecked()) { /* index = i */ }
}
RadioGroup 在 ScrollView 內滑動不流暢。解決:
rgGender.setOnTouchListener((v, event) -> { v.getParent().requestDisallowInterceptTouchEvent(true); return false; });
RadioGroup **自動保存/恢復** 選中 ID (依賴 android:id),無需手動處理 onSaveInstanceState。
**前提**:所有 RadioButton **必須有固定 ID** (XML 靜態指定或動態 View.generateViewId())。
// 獲取選中文本
fun RadioGroup.getCheckedText(): String? {
val id = checkedRadioButtonId
return if (id != -1) (findViewById(id)).text.toString() else null
}
// 監聽選中變化
fun RadioGroup.onCheckedChange(listener: (RadioButton?) -> Unit) {
setOnCheckedChangeListener { _, checkedId ->
listener.invoke(if (checkedId != -1) findViewById(checkedId) else null)
}
}
// 使用
rgGender.onCheckedChange { rb ->
tvQuestion.text = rb?.let { getString(R.string.toast_selected, it.text) }
}
掌握 RadioGroup 從資源分離到邏輯封裝的完整鏈路,配合進階樣式與動態操作,即可高效構建穩健、美觀、可維護的單選交互界面。