[基础控件]---对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“被点击”与“被选中”两项。

你可能感兴趣的:(checkbox)