//CheckBox示例:要本身建一个Activity //根据布局文件初始化 private CheckBox hobby1; private CheckBox hobby2; private CheckBox hobby3; private CheckBox hobby4; private CheckBox checkAll; hobby1 = (CheckBox) this.findViewById(R.id.hobby1); hobby2 = (CheckBox) this.findViewById(R.id.hobby2); hobby3 = (CheckBox) this.findViewById(R.id.hobby3); hobby4 = (CheckBox) this.findViewById(R.id.hobby4); checkAll = (CheckBox) this.findViewById(R.id.checkAll); //设置监听事件,定义一个有名字的监听类,之因此不用匿名内部类的形式,是由于有多个控件都要使用这个监听 private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { if (arg0.isChecked()) { Toast.makeText(MainActivity.this, "您选择了" + getResult(), Toast.LENGTH_SHORT).show(); } } }; // 获取多选项中的结果,利用isCheck()来判断那个被勾选了 public String getResult() { StringBuffer sb = new StringBuffer(); if (this.hobby1.isChecked()) { sb.append(hobby1.getText()); } if (this.hobby2.isChecked()) { sb.append(hobby2.getText()); } if (this.hobby3.isChecked()) { sb.append(hobby3.getText()); } if (this.hobby4.isChecked()) { sb.append(hobby4.getText()); } return sb.toString(); } // 给全选按钮设置单击监听事件,在布局中已经定义了监听,因此根据Id在这里获取监听 public void checkAll(View view) { switch (view.getId()) { case R.id.register: Toast.makeText(MainActivity.this, "您选择了" + getResult(), Toast.LENGTH_SHORT).show(); break; case R.id.checkAll: // 将全选按钮的单击状态给其余的复选框 boolean boovalue = this.checkAll.isChecked(); this.hobby1.setChecked(boovalue); hobby2.setChecked(boovalue); hobby3.setChecked(boovalue); hobby4.setChecked(boovalue); break; } } //布局文件 <CheckBox android:id="@+id/hobby1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="打篮球" /> <CheckBox android:id="@+id/hobby2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="游泳" /> <CheckBox android:id="@+id/hobby3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="跑步" /> <CheckBox android:id="@+id/hobby4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="LOL" /> <CheckBox android:id="@+id/checkAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全选/反选" android:onClick="checkAll"/> <Button android:id="@+id/register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="提交" android:onClick="checkAll"/>