简体   繁体   中英

How to go back to the previous Fragment on Press of a button

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?

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();

使用getFragmentManager().popBackStack()

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM