您的位置:首页 > 移动开发 > Android开发

android 中 CheckBox 复选框操作

2015-12-11 12:06 309 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息