为应用添加单选按钮

试用 Compose 方式
Jetpack Compose 是推荐在 Android 设备上使用的界面工具包。了解如何在 Compose 中添加组件。
<ph type="x-smartling-placeholder"></ph> 单选按钮 →

单选按钮可让用户从一组互斥的选项中选择一个 选项。如果用户需要查看所有可用选项,请使用单选按钮 。如果不需要显示所有选项,请使用 旋转图标

<ph type="x-smartling-placeholder">。 <ph type="x-smartling-placeholder">
</ph> Material.io 中的单选按钮示例
图 1.单选按钮示例 材质 设计

要创建各个单选按钮选项, RadioButton 。由于单选按钮是互斥的,因此请将它们分组到 一 RadioGroup。 系统确保只能从下列位置选择一个组内的一个单选按钮: 。

响应点击事件

当用户选择单选按钮时, RadioButton 对象接收点击事件。

以下示例显示了用户点按 群组中的 RadioButton 对象:

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pirates"/>
    <RadioButton android:id="@+id/radio_ninjas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ninjas"/>
</RadioGroup>

在托管此资源的 ActivityFragment 中 找到单选按钮,并为每个按钮设置一个更改监听器,如 如下:

Kotlin

findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Pirates is checked: $isChecked")
}

findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Ninjas is checked: $isChecked")
}

Java

findViewById<RadioButton>(R.id.radio_pirates).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Pirates is checked: $isChecked");
}

findViewById<RadioButton>(R.id.radio_ninjas).setOnCheckedChangeListener { buttonView, isChecked ->
    Log.d("RADIO", "Ninjas is checked: $isChecked");
}

在此示例中,当用户点按其中一个单选按钮时,系统将显示一条消息, 在 Logcat 中输出结果。

<ph type="x-smartling-placeholder">