YASAN
04/21/2021, 1:49 PMonBackPressed
to not let the user exit the app (its a launcher so that's the expected behavior).
But I have not found a way to check if the current destination is the main/last destination or if back stack is empty so I dont call super.onBackpressed
on that condition.YASAN
04/21/2021, 1:50 PMnavController.backStack.size
It tells me
NavController.getBackStack can only be called from within the same library group (groupId=androidx.navigation)
So I cannot check back stack size this wayYASAN
04/21/2021, 1:56 PMnavController.navigateUp()
onbackPressed without calling the super. It wont close the activity.Ian Lake
04/21/2021, 2:06 PMOnBackPressedDispatcher
and callbacks there - that's what Navigation uses alreadyIan Lake
04/21/2021, 2:08 PMBackHandler
or NavHost:
https://developer.android.com/reference/kotlin/androidx/activity/OnBackPressedDispatcher#hasenabledcallbacksYASAN
04/21/2021, 2:09 PMonBackPressed
?!YASAN
04/21/2021, 2:11 PMnavController.navigateUp()
and if it returns false it means I am at the end of backstackIan Lake
04/21/2021, 4:07 PMBackHandler { /* do nothing */ }
. That's it.YASAN
04/21/2021, 4:09 PMonNewIntent
& onBackPressed
YASAN
04/21/2021, 4:10 PMYASAN
04/21/2021, 4:11 PMnavigateUp()
returns false, it means the user is on home.YASAN
04/21/2021, 4:15 PMonNewIntent
to detect when the home button is tapped. Although its not the right way I assume, but I havent found any better ways yet. I should probably look into some source code from other launchers.YASAN
04/21/2021, 4:15 PMoverride fun onBackPressed() {
val onHome = !navController.navigateUp()
if (onHome) viewModel.toggleButtons()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val onHome = !navController.navigateUp()
if (onHome) viewModel.toggleButtons()
}
Ian Lake
04/21/2021, 4:16 PMBackHandler
your app ever uses. That's a pretty good sign that you've chosen the absolutely wrong approach. For two, navigateUp()
is also never the right thing to be calling here as that also is going to break deep linking from other apps. For three, if you ever find yourself overriding methods in your activity for a Compose app, you're most certainly not doing it the way you should be as Compose offers you the tools you need without doing thatIan Lake
04/21/2021, 4:17 PMBackHandler
Ian Lake
04/21/2021, 4:18 PMBackHandler { viewModel.toggleButtons() }
YASAN
04/21/2021, 4:19 PMYASAN
04/21/2021, 4:30 PMonNewIntent
override to this:
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
onBackPressed()
}
Although you said I should not override methods in my activity but I dont know if I can even detect when the Home button is tapped in compose? Is it even possible? Although I think this method is probably not the best way for non-compose layouts as well.Ian Lake
04/21/2021, 4:32 PMYASAN
04/21/2021, 4:32 PM