Android 使用AlertDialog实现多选并保存选中状态
程序员文章站
2022-05-29 09:57:20
...
先对要实现的效果做出描述:1、首次弹出对话框,如果有被选中的item,item的值设为true
2、可以随意选中和取消item
3、记录选中的状态
效果图:
public class MyActivity extent Activity{
private Map<Integer, String> map= new HashMap<>();
protected void onCreate(Bundle savedInstanceState){
setContentView(R.layout.main);
//AVo.list ,BVo.list 是解析json获得的数据(一般是集合)
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < AVo.list.size(); j++) {
for (int q = 0; q < BVo.list.size(); q++) {
if (BVo.list.get(q).equals(AVo.list.get(j))) {
map.put(j, BVo.get(q));
buffer.append(BVo.list.get(q) + ",");
}
}
}
button.setonClickListener(new View.OnClickListener(){
showDialog();
});
}
private void showDialog() {
//把获取的json数据解析后赋值给数组
String[] data=new String[AVo.list.size()];
boolean[] isCheck = new boolean[AVo.list.size()];
for(int i =0;i<AVo.list.size();i++){
data[i]=AVo.list.get(i);
if(map.containsKey(i)){
if(map.get(i).equals(AVo.list.get(i))){
isCkeck[i]=true;
}
}
}
AlertDialog.Builder ab = new AlertDialog.Builder(TaskDetailActivity.this);
ab.setTitle("请选择位置");
ab.setCancelable(false);
ab.setMultiChoiceItems(data, isCheck, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
isCheck[i] = b;
}
});
ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
StringBuffer buffer = new StringBuffer();
StringBuffer buffer1 = new StringBuffer();
@Override
public void onClick(DialogInterface dialogInterface, int i) {
for (int q = 0; q < isCheck.length; q++) {
if (isCheck[q] == true) {
buffer.append(data[q] + " ");
buffer1.append(data[q] + ",");
map.put(q, data[q]);
} else if (map.containsKey(q)) {
map.remove(q);
}
// isCheck[q] = false;
}
if (buffer.toString() != "") {
String str = buffer1.toString();
textview.setText("位置:" + buffer);
} else {
String str = buffer1.toString();
buffer.delete(0, buffer.length());
textview.setText("位置:" + buffer);
}
}
}
);
ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}
);
ab.create().show();
}
}