蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

2.3.5 RadioButton(单选按钮)与CheckBox(复选框)

核对 Android RadioButton/RadioGroup 单选互斥机制、CheckBox 多选监听与聚合读取、自定义 selector/style 勾选图标以及调整选择框相对方位与文字间距的方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

RadioButton 单选组互斥与取值方式

`RadioButton`(单选按钮)与 `CheckBox`(复选框)同属 `CompoundButton` 子类,核心差异在于单选互斥与多选独立(多页 `ListView` 中复选框的复用错位问题将在第 38 章专项剖析)。实现单选必须把同一组 `RadioButton` 放入 `RadioGroup` 容器中,可通过 `RadioGroup` 的 `android:orientation` 设置横向或纵向排列,并以 `android:checked="true"` 指定默认选中项。

读取单选结果主要有两种途径:第一,为 `RadioGroup` 注册 `setOnCheckedChangeListener`,在 `onCheckedChanged(group, checkedId)` 中即时按 `checkedId` 查出选中的 `RadioButton` 并读取文本——务必为每个 `RadioButton` 分配唯一 `android:id`,否则单选互斥与选中追踪将无法正常工作;第二,在用户点击提交按钮时,通过 `getChildCount()` 获取子项总数、循环调用 `getChildAt(i)` 取出每个 `RadioButton` 并以 `isChecked()` 判定当前选中项(也可直接调用 `radioGroup.getCheckedRadioButtonId()` 定位)。

CheckBox 多选监听与提交聚合

`CheckBox` 允许同时勾选多个选项,读取方式同样分为实时与批量两种:让 `Activity` 同时实现 `CompoundButton.OnCheckedChangeListener` 与 `View.OnClickListener`,在 `onCheckedChanged(compoundButton, isChecked)` 中响应单个复选框勾选变化,并在提交按钮的 `onClick()` 中逐一检查各 `CheckBox` 的 `isChecked()` 状态拼接全部已选条目。本站离线实验模拟了三项复选框交替勾选与取消,确认回调序列与最终提交集合完全一致。

自定义选择框图标、相对方位与间距调节

若默认主题样式不符合视觉规范,可编写基于 `state_enabled` 与 `state_checked` 双态切换的 `<selector>` 资源,并采用两种方式应用:其一直接在控件 XML 中设置 `android:button="@drawable/rad_btn_selctor"`;其二在 `styles.xml` 中定义继承自 `@android:style/Widget.CompoundButton.CheckBox` 的自定义样式 `<style name="MyCheckBox">` 覆盖 `android:button`,再在布局里通过 `style="@style/MyCheckBox"` 批量复用。

如需将选择框从文字左侧移到文字上方或右侧,分两步即可完成:先设 `android:button="@null"` 隐藏原生左侧按钮图标,再借助继承自 `TextView` 的 `android:drawableTop`(或 `drawableRight`/`drawableBottom`)挂载系统或自定义选择框 selector。如需拉大文字与选择框的间距,静态可在 XML 中调整 `android:paddingLeft`/`padding*`,动态则可在代码中读取目标 Drawable 的固有宽度 `getIntrinsicWidth() + 5` 后调用 `setPadding(rb_paddingLeft, 0, 0, 0)` 精确留白。

运行离线 RadioGroup 互斥监听、CheckBox 多选聚合、自定义样式及动态内边距核验

python · 阅读源码
"""Offline Android UI verifier for Ch 26: RadioButton and CheckBox."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

RADIO_GROUP_XML = """<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <RadioButton android:id="@+id/btnMan" android:text="男" android:checked="true" />
    <RadioButton android:id="@+id/btnWoman" android:text="女" />
</RadioGroup>
"""

CHECKBOX_SELECTOR_XML = """<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_checked="true" android:drawable="@mipmap/ic_checkbox_checked" />
    <item android:state_enabled="true" android:state_checked="false" android:drawable="@mipmap/ic_checkbox_normal" />
</selector>
"""

STYLE_XML = """<resources>
    <style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
        <item name="android:button">@drawable/rad_btn_selctor</item>
    </style>
</resources>
"""


@dataclass
class RadioBtn:
    rid: str
    text: str
    checked: bool = False


class RadioGroupModel:
    def __init__(self, buttons: list):
        self.buttons = buttons
        self.events = []

    def check(self, target_id: str) -> None:
        if not target_id:
            return
        for b in self.buttons:
            b.checked = (b.rid == target_id)
        selected = next((b.text for b in self.buttons if b.checked), None)
        self.events.append({"checkedId": target_id, "text": selected})

    def get_checked_via_loop(self) -> str:
        for i in range(len(self.buttons)):
            if self.buttons[i].checked:
                return self.buttons[i].text
        return ""


def main() -> None:
    rg_xml = ET.fromstring(RADIO_GROUP_XML)
    btns = []
    for ch in rg_xml:
        btns.append(RadioBtn(
            rid=ch.attrib.get(f"{ANDROID_NS}id", "").split("/")[-1],
            text=ch.attrib[f"{ANDROID_NS}text"],
            checked=ch.attrib.get(f"{ANDROID_NS}checked") == "true",
        ))
    rg = RadioGroupModel(btns)
    initial_selected = rg.get_checked_via_loop()
    rg.check("btnWoman")
    after_switch = rg.get_checked_via_loop()
    checked_count = sum(1 for b in rg.buttons if b.checked)
    c1_actual = {
        "orientation": rg_xml.attrib[f"{ANDROID_NS}orientation"],
        "all_have_id": all(bool(b.rid) for b in rg.buttons),
        "initial_selected": initial_selected,
        "after_switch": after_switch,
        "mutually_exclusive_count": checked_count,
        "listener_events": rg.events,
    }
    c1_expected = {
        "orientation": "horizontal",
        "all_have_id": True,
        "initial_selected": "男",
        "after_switch": "女",
        "mutually_exclusive_count": 1,
        "listener_events": [{"checkedId": "btnWoman", "text": "女"}],
    }

    # Case 2: CheckBox multi-select & submit
    cbs = {"cb_one": ["苹果", False], "cb_two": ["香蕉", False], "cb_three": ["橙子", False]}
    toasts = []
    for cid, state in (("cb_one", True), ("cb_three", True), ("cb_one", False), ("cb_two", True)):
        cbs[cid][1] = state
        if state:
            toasts.append(cbs[cid][0])
    submitted = [label for label, chk in cbs.values() if chk]
    c2_actual = {"change_toasts": toasts, "submitted_checked": submitted}
    c2_expected = {"change_toasts": ["苹果", "橙子", "香蕉"], "submitted_checked": ["香蕉", "橙子"]}

    # Case 3: Custom selector & style resolution
    sel_root = ET.fromstring(CHECKBOX_SELECTOR_XML)
    def pick(checked: bool) -> str:
        for item in sel_root.findall("item"):
            if item.attrib[f"{ANDROID_NS}state_enabled"] == "true" and (item.attrib[f"{ANDROID_NS}state_checked"] == "true") == checked:
                return item.attrib[f"{ANDROID_NS}drawable"]
        return ""
    st_node = ET.fromstring(STYLE_XML).find("style")
    c3_actual = {
        "checked_drawable": pick(True),
        "unchecked_drawable": pick(False),
        "style_name": st_node.attrib["name"],
        "style_button_item": st_node.find("item").text,
    }
    c3_expected = {
        "checked_drawable": "@mipmap/ic_checkbox_checked",
        "unchecked_drawable": "@mipmap/ic_checkbox_normal",
        "style_name": "MyCheckBox",
        "style_button_item": "@drawable/rad_btn_selctor",
    }

    # Case 4: Repositioning box (button=@null + drawableTop) & dynamic paddingLeft
    intrinsic_width_px = 42
    padding_left = intrinsic_width_px + 5
    c4_actual = {
        "reposition_button_attr": "@null",
        "reposition_drawable_attr": "android:drawableTop",
        "computed_padding_left_px": padding_left,
    }
    c4_expected = {
        "reposition_button_attr": "@null",
        "reposition_drawable_attr": "android:drawableTop",
        "computed_padding_left_px": 47,
    }

    cases = [
        {
            "name": "radiogroup_mutual_exclusion_and_id_guard",
            "summary": "验证 RadioGroup 单选互斥、唯一 ID 约束、监听回调与遍历 getChildAt/isChecked 读取",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "checkbox_multiselect_and_submit",
            "summary": "模拟多选 CheckBox 独立状态切换、单选回调记录与提交按钮聚合读取",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "custom_selector_and_style_resolution",
            "summary": "解析自定义 CheckBox selector 双态资源与 style 样式绑定",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "drawable_reposition_and_dynamic_padding",
            "summary": "验证 android:button=@null + drawableTop 改变选择框方位与动态计算 paddingLeft",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({
        "version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
        "cases": cases,
    }, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 RadioGroup 切换互斥与 ID 约束、3 项 CheckBox 独立勾选汇总、双态 selector/style 解析及 paddingLeft 计算。
运行离线 RadioGroup 互斥监听、CheckBox 多选聚合、自定义样式及动态内边距核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:12759d7c0a8244a63416041feb02164b94c995be32408c908e39ffc99536af60

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载2.3.5 RadioButton(单选按钮)与CheckBox(复选框)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:235aa51b21f60a08b1804f9819eec32333b64d470320d2e183c7f7556a48ea63

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如果在 `RadioGroup` 中忘记给某几个 `RadioButton` 编写 `android:id`,会产生什么问题?

展开参考解答

Android `RadioGroup` 依赖子 `RadioButton` 的唯一资源 ID 记录和维护当前选中项,缺失 ID 会导致单选互斥失效或无法取消先前选中状态。

规范与官方依据