Navigation drawer, handling the back button to go to previous fragments?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 11:34:24

Instead of:

fm.beginTransaction().replace(R.id.main, newFragment).addToBackStack("fragBack").commit();

Call:

fm.beginTransaction().add(R.id.main, newFragment).addToBackStack("fragBack").commit();

addToBackStack works with add.

replace function removes previous fragment and places new fragment so on your back-stack there is only one fragment all the time. So use add function to keep previous fragments on stack.

To always goto fragemnt1 from any fragment onBackPress try to do following:

getFragmentManager().popBackStack();
fm.beginTransaction().add(R.id.main, newFragment).addToBackStack("fragBack").commit();

this will remove last transaction from backstack and add new one. Try this.

Just wanted to report my findings even though this question is a little old for anyone else who may have had the same problem with the accepted answer. For me, doing the method suggested in the accepted answer, made the layers overlap, quickly making them unreadable. The code below (adapted from the accepted answer) avoids the overlaying but still adds the screen to the back stack.

fragmentManager.beginTransaction().replace(R.id.container, fragment).addToBackStack("fragBack").commit();

Hope this helps someone!

in some cases you have to use replace then you cant work with addtobackstack() so you can use this code in mainActivity. in this code when you press back key you always go to first Fragment( i call it HomeFragment ) and when you are in Home Fragment it ask twice time to go out from application (sorry for my poor English)

 private Boolean exit = false;
@Override
    public void onBackPressed() {
        if (exit) {
            super.onBackPressed();
            return;
        }

    try {
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag("HOME");
        if (fragment != null) {
            if (fragment.isVisible()) {
                this.exit = true;
                Toast.makeText(this, "Press Back again to Exit", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            fragment = HomeFragment.class.newInstance();
            getFragmentManager().popBackStack();
            fragmentManager.beginTransaction().replace(R.id.flContent, fragment, "HOME").commit();
        }
    } catch (Exception e) {

    }
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            exit = false;
        }
    }, 2000);
}
 - @Override
       public void onBackPressed() {
           DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
           int backstack = getSupportFragmentManager().getBackStackEntryCount();
           if (drawer.isDrawerOpen(GravityCompat.START)) {
               drawer.closeDrawer(GravityCompat.START);
           } else if (backstack > 0) {
              for (int i = 0; i < backstack; i++) {
                   getSupportFragmentManager().popBackStackImmediate();
            }
       } else {
           this.finish();
        }
    }

I would suggest avoiding an override of onBackPressed() altogether by managing your transactions properly in the first place. This will help to avoid having to implement crazy logic down the road.

To do this first we need to set a private class variable in that will enable initialization:

private boolean popNext = false;

The following code allows us to setup the initial back function by placing it on the stack. Every time thereafter, when popNext is set to true, we pop the initial transaction and push the new one. So we are replacing the 1>X transaction with the 1>Y transaction.

The extra embedded if statements deal with selecting the initial item, since we don't want to go from 1>1. If it's our initial case we just close the drawer. The other case needs to act like the back button, but we need to remember to set it as if it is returning to the initial state!

if(popNext){
    if(i == INITIAL_POSITION){
        onBackPressed();
        mDrawerLayout.closeDrawer(mDrawerList);
        popNext = false;
        return;
    }
    getFragmentManager().popBackStackImmediate();
}
else{
    if(i == INITIAL_POSITION){
        mDrawerLayout.closeDrawer(mDrawerList);
        return;
    }
    popNext=true;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();

Note: My code uses getFragmentManager() instead of getSupportFragmentManager() which is a native function, I believe as of Honeycomb.

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