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()
}
有没有办法做到这一点而不反思?