對於CheckBox的事件監聽不少朋友可能會首先想到使用CompoundButton的內部接口OnCheckedChangeListener,首先咱們來看CompoundButton控件,它繼承與Button,此種Button包含兩個狀態:選中與被選中(此Button被點擊時狀態會隨之改變),CompoundButton包含四個子類:CheckBox,RadioButton,Sswitch,ToggleButton它們都是用於狀態切換的控件。對於它們的事件監聽使用CompoundButton的內部接口CompoundButton.OnCheckedChangeListener符合標準要求。可是當狀態切換控件(CompoundButton)比較多的時候若是對每個控件都進行setOnCheckedChangeListener(new OnCheckedChangeListener() {})是很繁瑣的。那麼此時我接住如下方法進行實現會較爲快捷。html
一、先上xml佈局android
<?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>
二、對事件進行監聽在此說明,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: //一、點擊與否的事件監聽 Toast.makeText(this, "meat被點擊", Toast.LENGTH_SHORT).show(); //二、選中與否的事件監聽 if (checked){//選中 } else//未選中 break; case R.id.checkbox_cheese: //一、點擊與否的事件監聽 Toast.makeText(this, "cheese被點擊", Toast.LENGTH_SHORT).show(); //二、選中與否的事件監聽 if (checked){//選中 } else//未選中 break; } }
三、總結,在上面的例子當中,你固然能夠不去理會是否被點擊,直接在xml佈局當中使用android:checked=""屬性再在事件監聽當中直接switch(view.getId())進行監聽,這種方法不會出錯,可是此時在代碼就不能區分checkbox「被點擊」與「被選中」兩項。this