复选框允许用户从一组中选择一个或多个选项。通常,您应该在垂直列表中显示每个复选框选项。
要创建每个复选框选项,请CheckBox
在布局中创建一个。由于一组复选框选项允许用户选择多个项目,因此每个复选框都是单独管理的,您必须为每个复选框注册一个点击侦听器。
密钥类如下:
CheckBox
响应点击事件
当用户选中一个复选框时,CheckBox
对象将收到一个单击事件。
要定义复选框的单击事件处理程序,请将android:onClick
属性添加到XML布局中的 元素。此属性的值必须是要响应单击事件而调用的方法的名称。然后,
Activity
托管布局必须实现相应的方法。
例如,以下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
承载此布局的内,以下方法将处理两个复选框的click事件:
KOTLIN
fun onCheckboxClicked(view: View) { if (view is CheckBox) { val checked: Boolean = view.isChecked when (view.id) { R.id.checkbox_meat -> { if (checked) { // Put some meat on the sandwich } else { // Remove the meat } } R.id.checkbox_cheese -> { if (checked) { // Cheese me } else { // I'm lactose intolerant } } // TODO: Veggie sandwich } }}
JAVA
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 }}
您在android:onClick
属性中声明的方法必须具有完全如上所述的签名。具体来说,该方法必须:
公开
返回无效
定义一个
View
作为其唯一参数(这将View
是单击的参数)
提示:如果需要自己更改复选框状态,请使用setChecked(boolean)
或toggle()
方法。