正在调用 OnBackPressedCallback,但应用程序不会返回

编程入门 行业动态 更新时间:2024-10-26 00:19:21
本文介绍了正在调用 OnBackPressedCallback,但应用程序不会返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我最近更新了我的依赖项,将 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-23 03:45:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   OnBackPressedCallback

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!