android 中 CheckBox 复选框操作

来源:互联网 发布:小米盒子网络设置方法 编辑:程序博客网 时间:2024/05/01 18:47
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();          }      };  }

若是在 Layout 容器中使用 CheckBox,则要记录一个位置来设置 CheckBox

public String recordCheckBoxChecked() {            String checked = "";            int index = 1;            for (CheckBox cbx : checkBoxs) {                if (cbx.isChecked()) {                    checked = checked + index + ",";                }                index++;            }            return checked;        }
0 0
原创粉丝点击