Don't recreate the dialog, just toggle the checkboxes within the current dialog. Your onMultiChoiceClickListener can keep track of the currently active checkbox (if any) and uncheck it when another is selected. Here's a complete tested, working example:
package com.stackoverflow.beekeeper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
public class StackOverflowTest extends Activity {
/** Called when the activity is first created. */
@Override public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private int mSelected = -1;
@Override protected void onResume() {
super.onResume();
final Builder build = new Builder(this);
build.setTitle("List selection");
build.setCancelable(true);
final String[] strings = new String[]{"Cow", "Horse", "Goat"};
final OnMultiChoiceClickListener onClick =
new OnMultiChoiceClickListener() {
@Override public void onClick(final DialogInterface dialog,
final int which, final boolean isChecked) {
if (isChecked) {
if ((mSelected != -1) && (mSelected != which)) {
final int oldVal = mSelected;
final AlertDialog alert = (AlertDialog)dialog;
final ListView list = alert.getListView();
list.setItemChecked(oldVal, false);
}
mSelected = which;
} else
mSelected = -1;
}
};
build.setMultiChoiceItems(strings, null, onClick);
build.setPositiveButton("Done", new OnClickListener() {
@Override public void onClick(final DialogInterface dialog,
final int which) {
String message = null;
if (mSelected == -1)
message = "You didn't select anything.";
else
message = "You selected '" + strings[mSelected] + "'";
Toast.makeText(StackOverflowTest.this, message, Toast.LENGTH_LONG).show();
}
});
build.show();
}
}
One thing to watch for: you must specify "null" for the "checkedItems" parameter in your "setMultiChoiceItems" call -- otherwise the "setItemChecked" calls won't work as expected. It would end up using that array to store the checked state, and "setItemChecked" would'nt update it correctly, so everything would get confused. Odd, but true.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…