Home:ALL Converter>Intercept back navigation with Android Navigation Component

Intercept back navigation with Android Navigation Component

Ask Time:2020-06-20T04:31:29         Author:Iscle

Json Formatter

I'm trying to intercept the back navigation on an Android app to run some code before exiting the current fragment/activity.

The app is using Android Navigation Component, hooked up to a bottom navigation bar and a toolbar. The toolbar will show the back button when the stack is not empty.

What I'm trying to achieve is to show a custom dialog before exiting the fragment, asking the user if they want to save the data or not. My fragment contains a few EditText fields and a save button, that should be pressed to save the data to the repository. In case the user does not do this, then the popup should be shown when going back.

I've managed to intercept the android back button using a "OnBackPressedCallback", but the toolbar back button will still close the fragment.

Is there any way to intercept both methods (going back from the toolbar button, and with the android back button)?

Thanks

Author:Iscle,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62478153/intercept-back-navigation-with-android-navigation-component
nsk :

Have you tried to use navigation listener on toolbar?\n\nhttps://developer.android.com/reference/android/widget/Toolbar#setNavigationOnClickListener(android.view.View.OnClickListener)\n\nYou have to handle both cases separately, there is no single method for this case.",
2020-06-19T21:22:40
yy