问题
In a long-running operation, I'm showing a popup dialog (created from ProgressDialog
to prevent other operations from happening).
I have made it non-cancellable with setCancelable(false)
, so I can't close it using the back button, but surprisingly, the Search hardware button dismisses the dialog!
More exactly, the global search application is displayed, and when I come back to my app, the dialog has been dismissed.
Any idea how to prevent the dialog from being dismissed?
回答1:
This works (notice I put it on the dialog builder):
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getRepeatCount() == 0) {
return true; // Pretend we processed it
}
return false; // Any other keys are still processed as normal
}
})
Maybe it's even possible to grab the positive and negative button presses, and only handle these, return true for any other keys. Would be curious if you can figure that out...
PS: I read somewhere there are more "holes" in the dialog, i.e you can get rid of it without hitting any buttons on it. This was apparently one. Does anybody know of any others?
回答2:
setCanceledOnTouchOutside(false);
回答3:
mProgressDialog.setCancelable(false);
worked for me.
回答4:
You have to create your dialogs via the Activity's onCreateDialog event, as that is the point where they are managed by the Activity and they will be restored when the activity resumes.
Callback for creating dialogs that are managed (saved and restored) for you by the activity. If you use showDialog(int)
, the activity will call through to this method the first time, and hang onto it thereafter. Any dialog that is created by this method will automatically be saved and restored for you, including whether it is showing. If you would like the activity to manage the saving and restoring dialogs for you, you should override this method and handle any ids that are passed to showDialog(int). If you would like an opportunity to prepare your dialog before it is shown, override onPrepareDialog(int, Dialog)
.
Example usage:
public class MyClass extends Activity {
// ........ //
static final int DATE_DIALOG_ID = 1;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
}
return null;
}
public void launchSetDate() {
showDialog(DATE_DIALOG_ID);
}
}
来源:https://stackoverflow.com/questions/2502443/prevent-progressdialog-from-being-dismissed-when-i-click-the-search-button-andr