布局文件中添加如下内容:
<CheckBoxandroid:text="选项A"android:id="@+id/CheckBox01"android:layout_width="wrap_content"android:layout_height="wrap_content"></CheckBox>
<CheckBoxandroid:text="选项B"android:id="@+id/CheckBox02"android:layout_width="wrap_content"android:layout_height="wrap_content"></CheckBox>
<Buttonandroid:id="@+id/Button01"android:text="确定"android:layout_width="wrap_content"android:layout_height="wrap_content"></Button>
在代码activity类中定义如下:private CheckBox c1,c2 ;
private Button button;
在类activity的方法中添加如下内容:
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(Twoactivity.this, buttonView.getText()+"被选择",Toast.LENGTH_SHORT ).show();
}else{
Toast.makeText(Twoactivity.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(Twoactivity.this,buffer+"被选择", Toast.LENGTH_SHORT).show();
}
}