gpt4 book ai didi

java - 如何始终通过后退按钮返回到相同的 Activity ?

转载 作者:行者123 更新时间:2023-11-30 01:41:58 25 4
gpt4 key购买 nike

我有一个带有菜单的主要 Activity 。菜单项会导致其他 Activity 。我正在尝试实现它,以便当我从菜单启动新 Activity 时,按下后退按钮后,无论之前打开了多少其他 Activity ,应用程序都会返回到主 Activity 。

我尝试过使用 CLEAR_TOP 标志,但这不起作用。

menuItem.setOnClickListener(v -> {
Intent i = new Intent(AppMenuActivity.this, SomeActivity.class);
overridePendingTransition(0, 0);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
resideMenu.closeMenu();
});

最佳答案

来自FLAG_ACTIVITY_CLEAR_TOP安卓文档:

FLAG_ACTIVITY_CLEAR_TOP

public static final int FLAG_ACTIVITY_CLEAR_TOP

If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().

这是什么意思?

  • 如果您的 Activity 的启动模式是“多重/标准/默认”并且您没有在同一 Intent 中设置FLAG_ACTIVITY_SINGLE_TOP,那么它将完成并重新启动创建。
  • 如果您的 Activity 的启动模式不是“多重/标准/默认”或者您在同一 Intent 中设置了FLAG_ACTIVITY_SINGLE_TOP,则此 Intent 将传递到当前的 Activity实例的 onNewIntent()

因为您的 MainActivity 具有“默认”启动模式,并且您未在同一 Intent 中设置 FLAG_ACTIVITY_SINGLE_TOP,因此它将完成并重新创建。

但是您希望用户返回到 MainActivity 的当前实例,因此您需要在同一 Intent 中设置FLAG_ACTIVITY_SINGLE_TOP

只需更改您的代码

i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

关于java - 如何始终通过后退按钮返回到相同的 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com