Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Android Fragments in Backstack

I'm working on android fragments and i am unable to keep the fragments in backstack i-e when i press back button it pushes me out of the Activity which starts fragments, i want to go back to previous fragment on backpress.

So far i have tried this but i am unable to keep the fragments in backstack.

getActivity().getFragmentManager().beginTransaction()
             .replace(R.id.mainContainer, searchResultsFragment)
             .addToBackStack(null)
             .commit();
like image 661
MD Husnain Tahir Avatar asked Jan 07 '23 01:01

MD Husnain Tahir


1 Answers

before you call commit() to commit transaction, you should add fragment to backstack addToBackStack(null) as you did in your provided code

then override onBackPressed() to pop fragment from stack

the issue you facing , you make your transaction with FragmentManager

getActivity().getFragmentManager().beginTransaction()
             .replace(R.id.mainContainer, searchResultsFragment)
             .addToBackStack(null)
             .commit();

but you in onBackPressed() you using SupportFragmentManager

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0 ) {
        getSupportFragmentManager().popBackStack();         
    }
}

to fix your issue , you must know what you match your fragment type (in your case searchResultsFragment) I mean if its extend Fragment or support Fragment

in case you extend fragment support

import android.support.v4.app.Fragment;

you should use getSupportFragmentManager() in both transaction and onBackPressed

in case you use fragment

import android.app.Fragment;

you should use getFragmentManager() in both transaction and onBackPressed

like image 66
Mina Fawzy Avatar answered Jan 28 '23 16:01

Mina Fawzy