I'd like to know how properly handle system back button action using Navigation Controller. In my app I have two fragments (for ex. fragment1 and fragment2) and I have an action in fragment1 with destination to fragment2. Everything works well except one thing – when user presses system back button in fragment2 I want to show a dialog (using DialogFragment for example) to confirm exit. What is the best way to implement this behavior? If I use app:defaultNavHost="true"
in my host fragment then it automatically goes back ignoring my rules. And, additionally, what is this component for?
Should I use "pop to" may be?
Best Answer
Newest Update - April 25th, 2019
New release androidx.activity ver. 1.0.0-alpha07 brings some changes
More explanations in android official guide: Provide custom back navigation
Example:
Old Updates
UPD: April 3rd, 2019
Now its simplified. More info here
Example:
Deprecated (since Version 1.0.0-alpha06 April 3rd, 2019) :
Since this, it can be implemented just using JetPack implementation
OnBackPressedCallback
in your fragment and add it to activity:getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
Your fragment should looks like this:
UPD: Your activity should extends
AppCompatActivity
orFragmentActivity
and in Gradle file: