Reputation: 21
I have 2 fragments, one is added to the backstack, while the other one is not added. Consider that I'm in the 2nd fragment, which is not added to the backstack. There is a close button on top. On click of this button, I should go back to the previous fragment. How to achieve this? I tried something like this: But this can be done, only if its added to the back stack.
public void onCloseBtnClicked(Fragment fragment, FragmentActivity activity) {
if(fragment instanceof ImageFragment)
FragmentHelper.removeCurrentFragment(activity, fragment);
}
public static void removeCurrentFragment(final FragmentActivity activity, final Fragment fragment) {
if (fragment != null && !fragment.isDetached()) {
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.remove(fragment);
transaction.commitAllowingStateLoss();
}
}
This is not working, because I didn't add it to the backstack. Are there any methods to achieve this?
Upvotes: 0
Views: 2942
Reputation: 469
Before you commit the transaction with a new fragment, add it to the backstack:
transaction.addToBackStack(tag);
So when you wanna go back just:
if (mFragmentManager.getBackStackEntryCount() > 1) {
mFragmentManager.popBackStack();
}
Upvotes: 0
Reputation: 9408
Try getFragmentManager().popBackStack()
Also take a look at http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
If you use SupportFragment
try getSupportFragmentManager().popBackStack();
Upvotes: 1