首页 > 其他 > 详细

[基础控件]---对CheckBox事件监听处理

时间:2014-03-19 18:19:19      阅读:466      评论:0      收藏:0      [点我收藏+]

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

1、先上xml布局

bubuko.com,布布扣
<?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>
bubuko.com,布布扣

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

bubuko.com,布布扣
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;
        }
    }
bubuko.com,布布扣

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

[基础控件]---对CheckBox事件监听处理,布布扣,bubuko.com

[基础控件]---对CheckBox事件监听处理

原文:http://www.cnblogs.com/android001/p/3611775.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!