【问题标题】:Handling backpress on activity处理活动的压力
【发布时间】:2022-01-01 18:06:02
【问题描述】:

我在登录活动中有 2 个名为 Login 和 Main 的活动,有一个代码块可以实现此功能,如果我在 Main 活动中单击返回,它将关闭应用程序而不是返回登录活动,但我想处理后按和也许有一个对话框“你确定要退出应用程序?”或类似的东西。

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

此代码块在我的登录活动中

【问题讨论】:

标签: android authentication android-intent android-activity dialog


【解决方案1】:

将以下代码复制并粘贴到 MainActivity.java 中的 onBackPressed() 方法中。

new AlertDialog.Builder(MainActivity.this)
            .setTitle("Confirm close")
            .setMessage("Are you sure want to close app")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which {
                    finish();
                }
             }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which {
                   dialog.dismiss();
                 }
             }).create().show();

【讨论】:

  • 这就是我一直在寻找的谢谢。感谢您的回答
  • 我试过你的解决方案,但它给了我这个错误 E/WindowManager: android.view.WindowLeaked: Activity com.example.rtets.ui.activities.MainActivity has leaked window DecorView@ec13922[MainActivity] 那最初是在这里添加的
【解决方案2】:

如果用户已登录,您可以在 onBackPressed 中处理:

override fun onBackPressed() {
        if(!user.isLoggedIn()){
            val intent = Intent(this@LoginActivity, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(intent)
            finish()
        }else{
            //Show alert
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多