You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用getOnBackPressedDispatcher处理Fragment返回栈时的问题

问题原因

你在MainActivity中通过OnBackPressedCallback直接拦截了所有返回键事件,完全覆盖了Android默认的返回键处理逻辑。默认逻辑是:当Fragment回退栈存在未弹出的条目时,先弹出栈顶Fragment;只有回退栈为空时,才会触发Activity的退出操作。而你的当前实现跳过了Fragment回退栈的判断,不管栈内是否有Fragment,都直接执行延迟退出应用的逻辑,导致从Fragment按返回键时直接退出。

解决办法

修改MainActivity中的OnBackPressedCallback实现,先判断Fragment回退栈的条目数量,再决定执行Fragment回退还是应用退出:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // 检查Fragment回退栈是否有未弹出的条目
            FragmentManager fragmentManager = getSupportFragmentManager();
            if (fragmentManager.getBackStackEntryCount() > 0) {
                // 弹出栈顶Fragment,回到上一层界面
                fragmentManager.popBackStack();
            } else {
                // 回退栈为空,执行延迟退出逻辑
                exitAppWithDelay();
            }
        }
    });
}

private void exitAppWithDelay() {
    recyclerView.setVisibility(View.GONE);
    appBarLayout.setVisibility(View.GONE);
    goodbyText.setVisibility(View.VISIBLE);
    new Handler().postDelayed(() -> finish(), EXIT_DELAY);
}
额外优化建议

你Fragment中重启自身的代码会导致回退栈不断累积冗余条目,可简化为:

continueBtn.setOnClickListener(view -> {
    FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
    transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
            android.R.anim.fade_in, android.R.anim.fade_out);
    // 直接替换当前Fragment,不添加到回退栈(避免栈冗余)
    transaction.replace(R.id.fragment_container, new make_everything_ok_btn());
    transaction.commit();
});

内容的提问来源于stack exchange,提问作者Indie Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:33:37