android 给多个CheckBox注册监听事件

第一种

<?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_cheese" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@string/cheese" 
        android:onClick="onCheckboxClicked"/> 
</LinearLayout>

public void onCheckboxClicked(View view) {
        // Is the view now checked?
        boolean checked = ((CheckBox) view).isChecked()
        switch(view.getId()) {
            case R.id.checkbox_cheese:
                if (checked){//选中
                }
                break;
        }
    }

第二种

<?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_cheese" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@string/cheese" />
</LinearLayout>

 private CompoundButton.OnCheckedChangeListener ck=new CompoundButton.OnCheckedChangeListener() { 
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            boolean checked = isChecked;
            switch(buttonView.getId()) {
                case R.id.checkbox_cheese:
                    if(checked){        
                    }else{
                    }
                    break;
            }
        }
    };

CheckBox  cks = contentView.findViewById(R.id.checkbox_cheese);
        cbStateWC.setOnCheckedChangeListener(ck);

第三种

cks .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){}
            }
        });

你可能感兴趣的:(Android,android)