Search code examples
androidandroidxandroid-navigation

Android Navigation - confirm user navigation


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?


Solution

  • 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()
        }