Android multi activity/multi fragment app, how to allow back button to pop backstack and not quit activity?

197 views Asked by At

I am currently migrating a fairly complex app from overide on back pressed -> onBackPressedDispatcher.

However our previous code overode back press behaviour at the activity level, and i would like to overide from the fragment only where i need very specific back press behaviour, so as to enable predictive back. However what i have found is that the system back seems to pop the entire activity as opposed to popping the last fragment.

So my question is...how can we set android to pop fragments as opposed to activity without providing a custom callback to onbackPressedDispatcher?

Thanks!!!

private val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // Setting enabled true does not allow predictive back
        // Setting enabled false does not allow system back to pop fragments off backstack
}
1

There are 1 answers

2
Talha Chaudhry On

You can use the method of Activity getFragmentManager() and call its popBackStack. i.e,

getFragmentManager().popBackStack();

or

 getFragmentManager().popBackStackImmediate();