在导航组件的起始目标位置时如何处理后退按钮 [英] 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()

当我在图表上的任何地方时,它工作得很好,它使我返回,但是当我在它的开始时,由于后备箱为空,应用程序崩溃了.

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是否与我知道作为图根的ID相同,但我正在寻找更优雅的解决方案,例如是否存在当前位置的布尔标志该图是否为起始位置.

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天全站免登陆