I need to display custom AlertDialog, but only when there are no more fragments after calling NavController.navigateUp(). My current code does something similar, but there is a bug to it:

override fun onBackPressed() {

    if (navController.navigateUp()) {
        return
    }

    showQuitDialog()
}

This somewhat works, but if I cancel the AlertDialog and don't quit the app, navController already navigated up to NavGraph root, which is not the fragment in which I was when AlertDialog appeared. So, if I try to use any navigation action from that fragment, I get error:

java.lang.IllegalArgumentException: navigation destination com.example.test/actionNavigateToNextFragment is unknown to this NavController

如果我可以访问NavController中的mBackStack字段,这个问题就可以解决,但是它是package private,并且我不能在当前项目中使用反射.但是如果它是public,我会这样使用它:

override fun onBackPressed() {

    // 2 because first one is NavGraph, second one is last fragment on the stack
    if(navController.mBackStack.size > 2) { 
        navController.navigateUp()
        return
    }

    showQuitDialog()
}

有没有办法做到这一点而不反思?

推荐答案

You can compare the ID of the start destination with the ID of the current destination. Something like:

override fun onBackPressed() = when {
    navController.graph.startDestination == navController.currentDestination?.id -> showQuitDialog()
    else -> super.onBackPressed()
}

Hope it helps.

Kotlin相关问答推荐

当通过firstOrders访问时,存储在伴随对象中的对象列表具有空值

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

kotlin - 挂起简单方法调用链时可能存在冗余分支

Kotlin 协程按顺序执行,但仅在生产机器上执行

使用启动或使用 coroutineScope 启动协程之间的区别

在 Kotlin 中 import 如何找到文件路径?

如何在 Compose 中创建可重用的修饰符?

is return inside function definition 也是 kotlin 中的表达式

在 Kotlin 中,::class.simpleName是做什么的?

Kotlin 协程中的 Dispatchers.Main 和 Dispatchers.Default 有什么区别?

`this@classname` 在 Kotlin 中是什么意思?

更新到版本4.10.1/4.10.2后 Gradle 同步失败

如何在 Kotlin 中传递有界通配符类型参数?

Kapt不适用于Android Studio 3.0中的AutoValue

Kotlin:使用Gradle进行增量编译

使用范围的稀疏sparse值列表

任何处理器都无法识别以下选项:'[kapt.kotlin.generated, room.incremental]'

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

Kotlin:测试中的 java.lang.NoSuchMethodError

Android Jetpack Compose - 图像无法zoom 到框的宽度和高度