判断一组多选框至少有一个被选中_复选框

复选框允许用户从一组中选择一个或多个选项。通常,您应该在垂直列表中显示每个复选框选项。

9ddfb60c13d86ecafb3be17e5413eb57.png

要创建每个复选框选项,请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()方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值