zoukankan      html  css  js  c++  java
  • [基础控件]---对CheckBox事件监听处理

    对于CheckBox的事件监听很多朋友可能会首先想到使用CompoundButton的内部接口OnCheckedChangeListener,首先我们来看CompoundButton控件,它继承与Button,此种Button包含两个状态:选中与被选中(此Button被点击时状态会随之改变),CompoundButton包含四个子类:CheckBox,RadioButton,Sswitch,ToggleButton它们都是用于状态切换的控件。对于它们的事件监听使用CompoundButton的内部接口CompoundButton.OnCheckedChangeListener符合标准要求。但是当状态切换控件(CompoundButton)比较多的时候如果对每一个控件都进行setOnCheckedChangeListener(new OnCheckedChangeListener() {})是很繁琐的。那么此时我接住以下方法进行实现会较为快捷。

    1、先上xml布局

    <?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>

    2、对事件进行监听在此说明,CompoundButton“被点击”与“被选中”是两个完全不同的概念。这里我们借用View的onclick方法实现对此两个概念的区分与对多个chexbox的监听

    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:
                    //1、点击与否的事件监听
                    Toast.makeText(this, "meat被点击", Toast.LENGTH_SHORT).show();
                    //2、选中与否的事件监听
                    if (checked){//选中
                    }
                    else//未选中
                    break;
                case R.id.checkbox_cheese:
                    //1、点击与否的事件监听
                    Toast.makeText(this, "cheese被点击", Toast.LENGTH_SHORT).show();
                    //2、选中与否的事件监听
                    if (checked){//选中
                    }
                    else//未选中
                    break;
            }
        }

    3、总结,在上面的例子当中,你当然可以不去理会是否被点击,直接在xml布局当中使用android:checked=""属性再在事件监听当中直接switch(view.getId())进行监听,这种方法不会出错,但是此时在代码就不能区分checkbox“被点击”与“被选中”两项。

  • 相关阅读:
    angular2学习
    随笔
    angular 中ng-repeat后ng-click失效
    一个hover效果
    获取屏幕高度
    延时加载 lazyload使用技巧
    关于MVC模板渲染的一点小事type="text/template"
    JsRender实用教程(tag else使用、循环嵌套访问父级数据)
    jQuery Validate 插件为表单提供了强大的验证功能
    日期时间选择器bootstrap-datetimepicker表单组件
  • 原文地址:https://www.cnblogs.com/android001/p/3611775.html
Copyright © 2011-2022 走看看