Android nested AlertDialog - is this possible?

2019-01-27 04:30发布

问题:

I am trying to ask the user for confirmation twice before I do something irreversible to the database. The problem is that the outer click handler does not wait for the inner click handler. Once the Yes button is clicked on the first dialog, the 2nd dialog is displayed briefly, but the outer handler executes and completes nonetheless, ultimately destroying both dialogs.

new AlertDialog.Builder(ActivityMain.this).setMessage(
  "Are you sure?").setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {

    new AlertDialog.Builder(ActivityMain.this).setMessage(
      "Are you really sure?").setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {

    ....

Why is that?

回答1:

Just Design a new xml layout as your dialog and create a new activity and set it's theme to @android:style/Theme.Dialog in the manifest file under the activity tag ex:

<activity android:theme="@android:style/Theme.Dialog" android:name="LocationDialog"> </activity>

in the Dialog click listener code start the activity as

new AlertDialog.Builder(ActivityMain.this).setMessage(
  "Are you sure?").setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
             Intent i = new Intent(YourActivity.this, NewActivity.class);
             startActivity(i);
      }

This will start your new activity as a dialog where you can apply your action easily.



回答2:

I believe it's because dialogs are not blocking. As soon as they are displayed, processing moves on to the next line of code. The dialog is still displayed though, awaiting user interaction.