對於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“被點擊”與“被選中”兩項。