I use AndroidX Navigation component for fragment navigation inside my app. I have a scenario when I need to ask user whether he really wants to leave page or stay. I can do it easily for further navigation - just show AlertDialog and navigate on positive. However, I have real issues on stopping user from popping back with back button or using Drawer to navigate somewhere else. Also couldn't find anything useful like navigation listeners. How to catch navigation attempts inside Navigation Fragment?
Asked
Active
Viewed 105 times
1 Answers
1
As this doc says, you can add callback on onBackPressedDispatcher
and modify back pressed behavior:
val callback = onBackPressedDispatcher.addCallback(this) {
AlertDialog.Builder(this@Activity)
.setMessage("Are you sure?")
.setPositiveButton(android.R.string.ok, DialogInterface.OnClickListener { _, _ ->
handleOnBackPressed()
})
.setNegativeButton(android.R.string.cancel, null)
.create()
.show()
}

Alexander Zhukov
- 51
- 3
-
does it handle navigation from Drawer? – NapoleonTheCake Dec 09 '20 at 20:59
-
1@NapoleonTheCake, if you setup NavigationDrawer with NavController as it described [here](https://developer.android.com/guide/navigation/navigation-ui#add_a_navigation_drawer), no, there is no way to override default behavior. I suggest you to use navigation here manually, through listeners, and do same actions as for back pressed. – Alexander Zhukov Dec 10 '20 at 08:47
-
ended up locking (disabling) drawer from that screen as it was actually better for my case. – NapoleonTheCake Dec 18 '20 at 09:51