Back button closing app even when using FragmentTransaction.addToBackStack()

给你一囗甜甜゛ 提交于 2019-11-30 02:00:41
Bobbake4

You have to add the popBackStack() call to the onBackPressed() method of the activity.

Ex:

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

@Bobbake4's answer is awesome, but there is one little problem. Let's say I have three fragments A, B and C. A is the main Fragment (the fragment that shows when I launch my app), B and C are fragments I can navigate to from the navigation drawer or from A. Now, when I use the back button from B or C, I go back to the previous fragment (A) alright, but the title of the previous fragment (fragment B or C) now shows in the actionBar title of Fragment A. I have to press the back button again to "truly" complete the back navigation (to display the view and correct title for the fragment and returning to)

This is how I solved this problem. Declare these variables.

 public static boolean IS_FRAG_A_SHOWN = false;
 public static boolean IS_FRAG_B_SHOWN = false;
 public static boolean IS_FRAG_C_SHOWN = false;

In the MainActivity of my app where am handling navigation drawer methods, I have a method displayView(position) which handles switching of my fragments.

private void displayView(int position) {
    IS_FRAG_A_SHOWN = false;
    IS_FRAG_B_SHOWN = false;
    IS_FRAG_C_SHOWN = false;
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new FragmentA();
            IS_FRAG_A_SHOWN = true;
            break;
        case 1:
            fragment = new FragmentB();
            IS_FRAG_B_SHOWN = true;
            break;
        case 2:
            fragment = new FragmentC();
            IS_FRAG_C_SHOWN = true;
            break;

        default:
            break;
    }

finally, in my onBackPressed method, I do this:

public void onBackPressed() {
    if(fragmentManager.getBackStackEntryCount() != 0) {
        fragmentManager.popBackStack();
        if (IS_FRAG_A_SHOWN) { //If we are in fragment A when we press the back button, finish is called to exit
            finish();
        } else  {
            displayView(0); //else, switch to fragment A
        }

    } else {
        super.onBackPressed();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!