1.调用setOnCheckedChangeListener()方法,并把 CompoundButton.OnCheckedChangeListener实例作为参数传入
2.在CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中复选框的实例
[b]main.xml[/b]
[b]运行效果[/b]
[img]http://dl.iteye.com/upload/attachment/315087/39396fdd-91d6-3146-9da0-d2c43df181e4.png[/img]
2.在CompoundButton.OnCheckedChangeListener的onCheckedChanged()方法里,取得被选中复选框的实例
/** Called when the activity is first created. */
private CheckBox c1,c2 ;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
c1 = (CheckBox) findViewById(R.id.CheckBox01);
c2 = (CheckBox) findViewById(R.id.CheckBox02);
button = (Button) findViewById(R.id.Button01);
//注册事件监听
c1.setOnCheckedChangeListener(new CheckBoxListener());
c2.setOnCheckedChangeListener(new CheckBoxListener());
button.setOnClickListener(new ButtonClickListener());
}
//定义事件
class CheckBoxListener implements OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
//Toast
Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"被选择",Toast.LENGTH_SHORT ).show();
}else{
Toast.makeText(CheckBoxActivity.this, buttonView.getText()+"取消选择",Toast.LENGTH_SHORT ).show();
}
}
}
class ButtonClickListener implements OnClickListener{
String buffer = "";
public void onClick(View v) {
if(c1.isChecked())
buffer = buffer+c1.getText();
if(c2.isChecked())
buffer = buffer +c2.getText();
Toast.makeText(CheckBoxActivity.this, buffer+"被选择", Toast.LENGTH_SHORT).show();
}
}
[b]main.xml[/b]
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<CheckBox android:text="金钱" android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
<CheckBox android:text="地位" android:id="@+id/CheckBox02" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
<Button android:id="@+id/Button01" android:text="确定" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
[b]运行效果[/b]
[img]http://dl.iteye.com/upload/attachment/315087/39396fdd-91d6-3146-9da0-d2c43df181e4.png[/img]