为应用添加复选框

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

复选框可让用户从一组选项中选择一个或多个选项。通常情况下, 一个垂直列表中的各个选项

显示 Material.io 中的复选框示例的图片
图 1. 复选框 Material Design 复选框

要创建每个复选框选项,请创建一个 CheckBox。因为 一组复选框选项可让用户选择多个项目,每个复选框都是单独管理的, 并且你必须为每个事件注册点击监听器。

响应点击事件

首先创建一个在列表中包含 CheckBox 对象的布局:

?<xml version="1.0" encoding="utf-8"?>
L<inearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    C<heckBox android:id="@+id/checkbox_meat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Meat" />
    C<heckBox android:id="@+id/checkbox_cheese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cheese"/>
/<LinearLayout>

布局准备就绪后,前往 ActivityFragment,找到您的 CheckBox 视图,并设置更改监听器,如以下示例所示:

Kotlin

findViewById<CheckBox>(R.id.checkbox_meat)
    .setOnCheckedChangeListener { buttonView, isChecked ->
        Log.d("CHECKBOXES", "Meat is checked: $isChecked")
    }

findViewById<CheckBox>(R.id.checkbox_cheese)
    .setOnCheckedChangeListener { buttonView, isChecked ->
        Log.d("CHECKBOXES", "Cheese is checked: $isChecked")
    }

Java

findViewById<CheckBox>(R.id.checkbox_meat)
    .setOnCheckedChangeListener { buttonView, isChecked ->
        Log.d("CHECKBOXES", "Meat is checked: $isChecked");
    }

findViewById<CheckBox>(R.id.checkbox_cheese)
    .setOnCheckedChangeListener { buttonView, isChecked ->
        Log.d("CHECKBOXES", "Cheese is checked: $isChecked");
    }

每当复选框状态发生变化时,上面的代码都会在 Logcat 中输出一条消息。

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