在循环中的某些警报对话框之后返回上一个活动

时间:2016-03-30 16:25:30

标签: android alertdialog

在第二项活动中,我希望在循环中有一些警报对话框,如下所示:

  public void testAlert(View v)
        {
        AlertDialog alertDialog; 
        for (int k = 0; k< 4; k++){
           AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);        
           // set title
           alertDialogBuilder.setTitle("Title n. "+k);
           // set dialog message
           alertDialogBuilder
              .setMessage("Click OK to replace!")
              .setCancelable(false)
              .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog,int id) {
                 }
                })
              .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.dismiss();
                 }
              });
              // create alert dialog
              alertDialog = alertDialogBuilder.create();
              // show it
              alertDialog.show();

         } 
         finish();
  }

然后回到上一个活动,但是当我添加finish()时,我得到:

E/WindowManager( 9416): android.view.WindowLeaked: Activity com.example.secondscreen.Screen2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{422ae1f0 V.E..... R.....I. 0,0-480,275} that was originally added here
E/WindowManager( 9416):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
E/WindowManager( 9416):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
E/WindowManager( 9416):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/WindowManager( 9416):     at android.app.Dialog.show(Dialog.java:286)
E/WindowManager( 9416):     at com.example.secondscreen.Screen2.testAlert(Screen2.java:47)
E/WindowManager( 9416):     at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 9416):     at java.lang.reflect.Method.invoke(Method.java:515)
E/WindowManager( 9416):     at android.view.View$1.onClick(View.java:3855)
E/WindowManager( 9416):     at android.view.View.performClick(View.java:4508)
E/WindowManager( 9416):     at android.view.View$PerformClick.run(View.java:18675)
E/WindowManager( 9416):     at android.os.Handler.handleCallback(Handler.java:733)
E/WindowManager( 9416):     at android.os.Handler.dispatchMessage(Handler.java:95)
E/WindowManager( 9416):     at android.os.Looper.loop(Looper.java:136)
[...]

我该如何处理?

2 个答案:

答案 0 :(得分:2)

这是因为您打开一个对话框然后退出该活动。就像对话泄漏...

如果您想等待用户点击对话框,您必须在dialog.dismiss()

之后设置完成

答案 1 :(得分:0)

尝试

this.finish();

startActivity(new Intent(this,Previous.class));

如果符合您的要求。