如何在导航组件的起始目的地处理后退按钮 [英] How to handle back button when at the starting destination of the navigation component

本文介绍了如何在导航组件的起始目的地处理后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用新的导航组件,而且我真的很在意它!不过我确实有一个问题 - 当我处于图表的起始目的地时,我应该如何处理后退按钮?

I've started working with the new navigation component and I'm really digging it! I do have one issue though - How am I supposed to handle the back button when I'm at the starting destination of the graph?

这是我现在使用的代码:

This is the code I'm using now:

findNavController(this, R.id.my_nav_host_fragment)
                .navigateUp()

当我在图表上的任何位置时,它都运行良好,它会将我送回,但是当我在它的开始时 - 由于 backstack 为空,应用程序崩溃.

When I'm anywhere on my graph, it's working great, it send me back, but when I'm at the start of it - the app crashes since the backstack is empty.

这一切对我来说都有意义,我只是不知道如何处理.

This all makes sense to me, I'm just not sure how to handle it.

虽然我可以检查当前片段的 ID 是否与我所知道的图的根相同,但我正在寻找一个更优雅的解决方案,比如一些 bool 标志是否当前位置在图表是否为起始位置.

While I can check if the current fragment's ID is the same as the one that I know to be the root of the graph, I'm looking for a more elegant solution like some bool flag of wether or not the current location in the graph is the starting location or not.

想法?

推荐答案

我有一个类似的场景,我想在到达起始目的地时完成活动,并在导航进一步向下时执行常规的navigateUp"图形.我通过一个简单的扩展函数解决了这个问题:

I had a similar scenario where I wanted to finish the activity when I was at the start destination and do a regular 'navigateUp' when I was further down the navigation graph. I solved this through a simple extension function:

fun NavController.navigateUpOrFinish(activity: AppCompatActivity): Boolean {
return if (navigateUp()) {
    true
} else {
    activity.finish()
    true
}

}

然后这样称呼它:

override fun onSupportNavigateUp() = 
        findNavController(R.id.nav_fragment).navigateUpOrFinish(this)

但是,我无法使用 NavigationUI,因为每当我到达起始目的地时,它都会隐藏后退箭头.所以,而不是:

However I was unable to use NavigationUI as this would hide the back arrow whenever I was at the start destination. So instead of:

NavigationUI.setupActionBarWithNavController(this, controller)

我手动控制了主页图标:

I manually controlled the home icon:

setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_navigation_back)

这篇关于如何在导航组件的起始目的地处理后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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