如何显示一个对话框以确认用户是否希望退出Android活动?

Pet*_*r A 269 android activity-finish android-dialog android-activity

我一直试图表现出"你想退出吗?" 用户尝试退出活动时的对话框类型.

但是我找不到合适的API挂钩. Activity.onUserLeaveHint()最初看起来很有希望,但我找不到阻止活动完成的方法.

jax*_*jax 389

在Android 2.0+中,这看起来像:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing Activity")
        .setMessage("Are you sure you want to close this activity?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .setNegativeButton("No", null)
    .show();
}
Run Code Online (Sandbox Code Playgroud)

在早期版本中,它看起来像:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
                YourClass.this.finish();    
            }

        })
        .setNegativeButton(R.string.no, null)
        .show();

        return true;
    }
    else {
        return super.onKeyDown(keyCode, event);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 同样在2.0及以上版本中有一个新的onBackPressed事件,推荐使用onKeyDown http://developer.android.com/intl/zh-TW/reference/android/app/Activity.html#onBackPressed()这里有一节谈论变化和新推荐的方法.http://developer.android.com/intl/zh-TW/sdk/android-2.0.html (15认同)
  • 关于捕获后退键的博客文章:http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html请注意,这不允许你抓住其他用户可以离开您的应用的方式:回家,选择通知,接听电话等. (3认同)

Cha*_*dla 181

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   ExampleActivity.super.onBackPressed();
               }
           })
           .setNegativeButton("No", null)
           .show();
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个更好,更好的解决方案,谢谢 (8认同)
  • elBradford发表评论:调用超级onBackPressed比假设onBackPressed只调用finish()更好.即使现在也是如此,未来的API`CustomTabActivity.super.onBackPressed可能不是这样. (5认同)

sur*_*ain 33

修改了@ user919216代码..并使其与WebView兼容

@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();

    }
    else
    {
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();
    }

}
Run Code Online (Sandbox Code Playgroud)


Ton*_*mez 22

我更喜欢双击后退按钮而不是退出对话框退出.

在此解决方案中,它会在第一次返回时显示吐司,警告另一次按下将关闭应用程序.在这个例子中不到4秒.

private Toast toast;
private long lastBackPressTime = 0;

@Override
public void onBackPressed() {
  if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
    toast = Toast.makeText(this, "Press back again to close this app", 4000);
    toast.show();
    this.lastBackPressTime = System.currentTimeMillis();
  } else {
    if (toast != null) {
    toast.cancel();
  }
  super.onBackPressed();
 }
}
Run Code Online (Sandbox Code Playgroud)

令牌来自:http://www.androiduipatterns.com/2011/03/back-button-behavior.html


GLe*_*Lee 21

如果您不确定对"返回"的调用是否会退出应用程序,或者将用户带到另一个活动,您可以将上述答案包装在一个支票isTaskRoot()中.如果您的主活动可以多次添加到后台堆栈,或者您正在操纵后台堆栈历史记录,则会发生这种情况.

if(isTaskRoot()) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                YourActivity.super.onBackPressed;
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
    AlertDialog alert = builder.create();
    alert.show();

} else {
    super.onBackPressed();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用Lambda:

    new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
        .setTitle(getString(R.string.info))
        .setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
            moveTaskToBack(true);
            finish();
        })
        .setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
        })
        .show();
Run Code Online (Sandbox Code Playgroud)

您还需要在gradle.build中设置级别语言以支持java 8:

compileOptions {
       targetCompatibility 1.8
       sourceCompatibility 1.8
}
Run Code Online (Sandbox Code Playgroud)


Siw*_*申思维 5

在中国,大多数应用程序将通过"点击两次"确认退出:

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 
Run Code Online (Sandbox Code Playgroud)


Anj*_*tix 5

首先super.onBackPressed();onbackPressed()方法中删除代码以下代码:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

}
Run Code Online (Sandbox Code Playgroud)