CheckBoxActivity.java

 

package archie.android.activity; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; public class CheckBoxActivity extends Activity { private TextView textView; private CheckBox checkBox1; private CheckBox checkBox2; private CheckBox checkBox3; private CheckBox checkBox4; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView=(TextView) findViewById(R.id.TextView01); checkBox1=(CheckBox) findViewById(R.id.CheckBox01); checkBox2=(CheckBox) findViewById(R.id.CheckBox02); checkBox3=(CheckBox) findViewById(R.id.CheckBox03); checkBox4=(CheckBox) findViewById(R.id.CheckBox04); button=(Button) findViewById(R.id.button1); checkBox1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(checkBox1.isChecked()){ DisplayToast("你选择了:"+checkBox1.getText()); } }}); checkBox2.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(checkBox2.isChecked()){ DisplayToast("你选择了:"+checkBox2.getText()); } }}); checkBox3.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(checkBox3.isChecked()){ DisplayToast("你选择了:"+checkBox3.getText()); } }}); checkBox4.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(checkBox4.isChecked()){ DisplayToast("你选择了:"+checkBox4.getText()); } }}); button.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { int num=0; if(checkBox1.isChecked()){ num++; } if(checkBox2.isChecked()){ num++; } if(checkBox3.isChecked()){ num++; } if(checkBox4.isChecked()){ num++; } DisplayToast("你一共选择了:"+num+"项"); }}); } public void DisplayToast(String str){ Toast toast=Toast.makeText(this, str, Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP, 0, 220); toast.show(); } }

 

main.xml

 

<?xml version="1.0" encoding="utf-8"?>