Code Poet
Code Poet

Reputation: 11447

How to make android dialog modal?

I implemented this custom AlertDialog like so:

AlertDialog dialog = new AlertDialog.Builder(this)
    .setView(dialogView)
    .setTitle(getResources().getString(R.string.addedit_asklater_price))
    .setCancelable(false)
    .create();

    dialog.setMessage(text);
    dialog.setOwnerActivity(this);
    dialog.setButton(...)
    dialog.setButton(...)
    dialog.show();

    doProcessUserInput();

However, I notice that after the dialog.show() control immediately flows to doProcessUserInput() without waiting for the user to dismiss the dialog using any of the dialog buttons.

This behavior seems bizarre, I was expecting the dialog to be modal, in the way I have always known modal dialogs to be.

I can restructure my code so that doProcessUserInput() is called from the dialog button's onClickListener. I was however wondering if there was a way to pause program execution at dialog.show() untill the dialog is finished.

PS:

  1. I've tried using a Custom Dialog that extends Dialog, but it has the same problem. I am creating the dialog in a button's onClickListener.
  2. I've tried implementing the Activity::onCreateDialog and using showDialog(id) instead of dialog.show(), but that has the same problem.

Upvotes: 5

Views: 12844

Answers (4)

ori888
ori888

Reputation: 750

Before calling the dialog show() method, try calling .setCancelable(false). That worked perfectly for me.

Upvotes: 4

Peri Hartman
Peri Hartman

Reputation: 19484

This works for me: create an Activity as your dialog. Then,

  1. Add this to your manifest for the activity:

    android:theme="@android:style/Theme.Dialog"

  2. Add this to onCreate of your activity

    setFinishOnTouchOutside (false);

  3. Override onBackPressed in your activity:

    @Override public void onBackPressed() { // prevent "back" from leaving this activity }

The first gives the activity the dialog look. The latter two make it behave like a modal dialog.

Upvotes: 4

Ramseys
Ramseys

Reputation: 431

Furthermore, you shouldn't block the application flow in a dialog.

Android dev guide and community best practices states that if you want something modal, you have to do it in the onClickListeners.

Upvotes: 2

Alexander
Alexander

Reputation: 48272

Surely, you can set up onPositiveButton click listener for your dialog and do your action from that listener.

If you indeed want to pause your activity at a certain point you, probably, can use the old java wait/notify mechanism or more convenient new mechanisms such as executors.

Why would you want to do that though is not clear. Android dialogs are specifically designed to be non-modal so that they can in no way block your application (as your application can include other activities such as native Phone Call activity and it would be bad if those get blocked).

Upvotes: 4

Related Questions