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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With