复选框(Checkboxes)

Checkbox(多选框)可以让用户从一系列选项里选择一个或者多个选项.比较典型的是像下图这样在一个垂直列表里选择可选项:

创建checkbox需要在layout文件中添加<CheckBox>标签,因为可以多选,所以需要为每个checkbox添加一个监听事件.

处理点击事件

当用户选择一个checkbox的时候,CheckBox对象会收到一个点击事件,跟Button一样,我们可以通过Android:onClick属性来为checkbox指定一个处理点击事件的方法. 比如这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <CheckBox android:id="@+id/checkbox_meat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/meat"
        android:onClick="onCheckboxClicked"/>
    <CheckBox android:id="@+id/checkbox_cheese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cheese"
        android:onClick="onCheckboxClicked"/>
</LinearLayout>

然后我们可以在Activity中实现onCheckboxClicked()方法来处理checkbox的点击事件:

public void onCheckboxClicked(View view) {
    // Is the view now checked?
    boolean checked = ((CheckBox) view).isChecked();

    // Check which checkbox was clicked
    switch(view.getId()) {
        case R.id.checkbox_meat:
            if (checked)
                // Put some meat on the sandwich
            else
                // Remove the meat
            break;
        case R.id.checkbox_cheese:
            if (checked)
                // Cheese me
            else
                // I'm lactose intolerant
            break;
        // TODO: Veggie sandwich
    }
}

跟button的onClick方法一样,需要满足几个条件:

  • 必须是public方法

  • 必须返回void

  • 拥有一个唯一的View参数.

如果我们需要通过代码修改checkbox的状态(必须要加载一个保存的CheckBoxPreference),我们可以使用setChecked(Boolean)或者toggle()方法.

Copyright© 2020-2022 li-xyz 冀ICP备2022001112号-1