我有一个警告对话框,其中包含多个列表选择侦听器。问题是当我在选择多个项目后打开第一个对话框时,按下正面按钮,然后在重新打开警告对话框中,它显示没有选择上次打开时我选择的项目。
final CharSequence[] dialogList= list.toArray(new CharSequence[list.size()]);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(SchoolFieldsData.this);
builderDialog.setTitle("Enter Average Fee");
int count = dialogList.length;
boolean[] is_checked = new boolean[count]; // set is_checked boolean false;
// Creating multiple selection by using setMutliChoiceItem method
builderDialog.setMultiChoiceItems(dialogList, is_checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
}
});
builderDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ListView list = ((AlertDialog) dialog).getListView();
// make selected item in the comma seprated string
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
if (stringBuilder.length() > 0) stringBuilder.append(",");
stringBuilder.append(list.getItemAtPosition(i));
}
}
/*Check string builder is empty or not. If string builder is not empty.
It will display on the screen.
*/
if (stringBuilder.toString().trim().equals("")) {
// ((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
stringBuilder.setLength(0);
} else {
// ((TextView) findViewById(R.id.text)).setText(stringBuilder);
}
}
});
builderDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// ((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
}
});
AlertDialog alert = builderDialog.create();
alert.show();
答案 0 :(得分:1)
这是因为每次调用此代码时都会构建一个新的AlertDialog(第2行),并为其提供新的objMyList
数组。
尝试恢复状态,例如将is_checked
数组保存在不同的位置,并在正向按钮处理程序中将状态保存到此数组(而不是行is_checked
)。