AlertDialog's setCancelable(false) method not

2019-01-14 00:04发布

问题:

I had created an AlertDialog which is working fine. It is disappearing, if I press:
1) escape keyboard button or
2) back button using mouse
To make it stay focused even on above stated conditions, I had added '.setCancelable(false)' statement while building. But, I still see dialog disappearing. Where is the problem? Please help.

Code added:

return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setCancelable(false)
                .setPositiveButton(R.string.alert_dialog_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doPositiveClick();
                        }
                    }
                )
                .setNegativeButton(R.string.alert_dialog_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doNegativeClick();
                        }
                    }
                )
                .create();


Env: Android 4.0 on XP Professional.

回答1:

Is this your complete code? then please change your code for setting setCancelable(false) like this

void showDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance(
            R.string..alert_dialog_two_buttons_title);
    newFragment.setCancelable(false);
    newFragment.show(getFragmentManager(), "dialog");
}


回答2:

Your dialog is set to no-cancelable, but your host fragment is still cancelable. Set your fragment with setCancelable(false).



回答3:

Another working example:

Step 1

Create class:

public class DialogActivity extends android.app.DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.myMessage);
        setCancelable(false);
        return builder.create();
   }
}

Step 2

Add method to your Activity:

private boolean showDialog() {
    FragmentManager manager = getFragmentManager();
    DialogActivity dialogActivity;
    dialogActivity = new DialogActivity();
    dialogActivity.show(manager, "DialogActivity");
    return true;
}

Step 3

Call showDialog() when you need to show dialog



回答4:

dialog.setCanceledOnTouchOutside(false);

setCanceledOnTouchOutside(boolean)

Sets whether this dialog is canceled when touched outside the window's bounds. If setting to true, the dialog is set to be cancelable if not already set.