Android nested AlertDialog - is this possible?

2019-01-27 04:47发布

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?

2条回答
时光不老,我们不散
2楼-- · 2019-01-27 05:20

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.

查看更多
祖国的老花朵
3楼-- · 2019-01-27 05:36

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.

查看更多
登录 后发表回答