import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
public class MainHelloCheckBox extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 声明对象
final CheckBox cb1 = (CheckBox) findViewById(R.id.CheckBox01);
final CheckBox cb2 = (CheckBox) findViewById(R.id.CheckBox02);
// 声明监听器
OnClickListener ocl = new OnClickListener() {
@Override
public void onClick(View v) {
if (!((CheckBox) v).isChecked()) {
Toast.makeText(MainHelloCheckBox.this,
"\"" + ((Button) v).getText() + "\"被取消",
Toast.LENGTH_SHORT).show();
}
}
};
OnCheckedChangeListener occl = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
Toast.makeText(MainHelloCheckBox.this,
"\"" + buttonView.getText() + "\"被选择",
Toast.LENGTH_SHORT).show();
}
}
};
// 绑定监听器
cb1.setOnCheckedChangeListener(occl);
cb2.setOnCheckedChangeListener(occl);
cb1.setOnClickListener(ocl);
cb2.setOnClickListener(ocl);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选择你想得到的东西:" />
<CheckBox
android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="得不到" >
</CheckBox>
<CheckBox
android:id="@+id/CheckBox02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="已失去" >
</CheckBox>
</LinearLayout>