CheckBox cb_remember=(CheckBox)findViewById(R.id.cb_remember);
cb_remember.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id=buttonView.getId();
Toast.makeText(getApplicationContext(), "123:"+id , Toast.LENGTH_LONG.show();
}});
Toast显示的是 123:2131165489 所以说 buttonView 通常用于获取某个checkbox的id 可用于多选。 isChecked用于确定是否被选中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="多选" />
<CheckBox
android:id="@+id/check1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="爱吃苹果"
/>
<CheckBox
android:id="@+id/check2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="爱吃橡胶"
/>
<CheckBox
android:id="@+id/check3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="爱吃便便"
/>
</LinearLayout>
package com.wang.checkbox;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
private CheckBox check2, check3, check1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check2 = (CheckBox) findViewById(R.id.check2);
check1 = (CheckBox) findViewById(R.id.check1);
check3 = (CheckBox) findViewById(R.id.check3);
check2.setOnCheckedChangeListener(listener);
check1.setOnCheckedChangeListener(listener);
check3.setOnCheckedChangeListener(listener);
}
private OnCheckedChangeListener listener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
switch (buttonView.getId()) {
case R.id.check1:
Toast.makeText(getApplication(), "爱吃苹果", 0).show();
break;
case R.id.check2:
Toast.makeText(getApplication(), "爱吃橡胶", 0).show();
break;
case R.id.check3:
Toast.makeText(getApplication(), "爱吃便便", 0).show();
break;
default:
break;
}
}
};
}