Catch back and up navigation on fragment

 

What to do if you need to implement an action when the user presses the button to return to the previous screen (both the up button and the back button) on a Fragment? In this case, the FragmentManager.OnBackStackChangedListener listener can help, as it is fired whenever the fragment is added and removed from the back stack. Just be careful as it is not only when the fragment is removed from the back stack, but also when it is added.

How to implement it?

In the fragment's method onCreate, create a FragmentManager.OnBackStackChangedListener and add it to the parentFragmentManager with the method addOnBackStackChangedListener(). The code below show an example.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
parentFragmentManager.addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener {
//do something
})
}