正在调用 OnBackPressedCallback,但应用程序不会返回 [英] OnBackPressedCallback is being called, but app is not going back

查看:27
本文介绍了正在调用 OnBackPressedCallback,但应用程序不会返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近更新了我的依赖项,将 OnBackPressedCallback 从接口更改为抽象类.

I recently updated my dependencies to include the OnBackPressedCallback change from an interface into an abstract class.

我已根据新文档进行设置此处 但我觉得事情并没有像他们应该的那样运作.

I have set things up according to the new documentation here but I feel like things are not working as they should.

我的片段的 OnCreate 看起来很像文档:

My fragment's OnCreate looks a lot like the documentation:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireActivity().onBackPressedDispatcher.addCallback(this) {
            backPressed()
    }
}

当我按下后退按钮时,backPressed() 中的代码会运行,但什么也没有发生.

When I press the back button, the code in backPressed() is run, but nothing more happens.

我已经尝试调用 handleBackPressed()requireActivity().onBackPressedDispatcher.onBackPressed()requireActivity().onBackPressed()在回调内部,但这些都会导致 StackOverflowError 因为它似乎递归地运行该回调.

I have tried calling handleBackPressed() and requireActivity().onBackPressedDispatcher.onBackPressed() and requireActivity().onBackPressed() from inside the callback, but those all cause a StackOverflowError because it seems to run that callback recursively.

一定有一些很明显的东西我遗漏了......

There has got to be something really obvious I am missing...

推荐答案

当您注册 OnBackPressedCallback 时,您就负责处理后退按钮.这意味着当您收到回调时,不会发生其他按下后退的行为.

When you register an OnBackPressedCallback, you are taking on the responsibility for handling the back button. That means that no other on back pressed behavior is going to occur when you get a callback.

如果您使用导航,您可以使用您的NavController 弹出返回堆栈:

If you're using Navigation, you can use your NavController to pop the back stack:

requireActivity().onBackPressedDispatcher.addCallback(this) {
    backPressed()
    // Now actually go back
    findNavController().popBackStack()
}

这篇关于正在调用 OnBackPressedCallback,但应用程序不会返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆