- public class MainActivity extends Activity {
- // 声明多选列表对象
- private CheckBox cbx1, cbx2, cbx3, cbx4;
- private List<CheckBox> checkBoxs = new ArrayList<CheckBox>();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- cbx1 = (CheckBox) findViewById(R.id.checkBox1);
- cbx2 = (CheckBox) findViewById(R.id.checkBox2);
- cbx3 = (CheckBox) findViewById(R.id.checkBox3);
- cbx4 = (CheckBox) findViewById(R.id.checkBox4);
- // 默认选项
- cbx1.setChecked(true);
- cbx3.setChecked(true);
- cbx1.setOnCheckedChangeListener(listener);
- cbx2.setOnCheckedChangeListener(listener);
- cbx3.setOnCheckedChangeListener(listener);
- cbx4.setOnCheckedChangeListener(listener);
- // 添加到集合中
- checkBoxs.add(cbx1);
- checkBoxs.add(cbx2);
- checkBoxs.add(cbx3);
- checkBoxs.add(cbx4);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- public void getValues(View v) {
- String content = "";
- for (CheckBox cbx : checkBoxs) {
- if (cbx.isChecked()) {
- content += cbx.getText() + "\n";
- }
- }
- if ("".equals(content)) {
- content = "您还没有选择呢";
- }
- new AlertDialog.Builder(this).setMessage(content).setTitle("选中的内容如下")
- .setPositiveButton("关闭", null).show();
- }
- CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView,
- boolean isChecked) {
- CheckBox box = (CheckBox) buttonView;
- Toast.makeText(getApplicationContext(),
- "获取的值:" + isChecked + "xxxxx" + box.getText(),
- Toast.LENGTH_LONG).show();
- }
- };
- }