Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

提个bug,拦截返回事假会使 其他的fragment无法通过onBackPressedDispatcher拦截返回事件 #25

Closed
ppg408331701 opened this issue Jun 30, 2020 · 1 comment

Comments

@ppg408331701
Copy link

    override fun onBackPressed() {
        val nav = Navigation.findNavController(this, R.id.nav_host_fragment)
        if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.mainFragment) {
            //如果当前界面不是主页,那么直接调用返回即可
            nav.navigateUp()
        } else {
            //是主页
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.showShort("再按一次退出程序")
                exitTime = System.currentTimeMillis()
            } else {
                super.onBackPressed()
            }
        }
    }

这样子重写MainActivity的onBackPressed()方式拦截返回事假会使 其他的fragment无法通过onBackPressedDispatcher拦截返回事件。
参考:https://developer.android.google.cn/guide/navigation/navigation-custom-back#kotlin
参考:https://www.jianshu.com/p/aec2cde0a5f0

我目前是在MainFragment添加onBackPressedDispatcher拦截返回键,处理返回2次退出app事件
在SubFragment添加onBackPressedDispatcher,拦截返回键,处理之前提到的Navigation 的出栈事件

@ppg408331701 ppg408331701 changed the title 提个bug, 提个bug,拦截返回事假会使 其他的fragment无法通过onBackPressedDispatcher拦截返回事件 Jun 30, 2020
@hegaojian
Copy link
Owner

你这种写法是正确的 , 感谢你的提醒和解决方案

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants