Updating the Navigation Drawer (with DrawerLayout)

2019-04-09 23:29发布

I am designing an app on the Android with a Navigation Drawer. Lets say I navigate through fragments and go from Fragment 1 to Fragment 2. Everything works fine but when I am in Fragment 2 (which loads from the navigation drawer) and click the system back button althought I get the previous fragment (I use addToBackStack) the navigation drawer doesn't get updated and the cell of Fragment 2 is highlighted. What should I do to fix this?

2条回答
迷人小祖宗
2楼-- · 2019-04-10 00:21

Found the solution:

Added a tag in every addToBackStack. So the code if I call addToBackStack it looks like this:

addToBackStack("Fragment1");
addToBackStack("Fragment2");

whenever I put each fragment to the stack. Then I override the back button pressed:

@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentManager fm = getSupportFragmentManager();
    String stackName = null;
    for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
        stackName = fm.getBackStackEntryAt(entry).getName();
        Log.i("BC", "stackEntry" + entry);
    }
    if (stackName == "Fragment1"){
        mDrawerList.setItemChecked(0, true);
    } else if (stackName == "Fragment2") {
        mDrawerList.setItemChecked(1, true);
    }
}
查看更多
一夜七次
3楼-- · 2019-04-10 00:25

The question is 2 years old and the answer of @alecnash is working. But in my opinion he is misappropriating the onBackPressed() method... and for later googler:

Better use an OnBackStackChangedListener. In this approach you need not to override the onBackPressed() which you probably need for somethingelse. Together with the code from @alecnash the listener looks like:

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                FragmentManager fm = getSupportFragmentManager();
                String stackName = null;
                for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
                    stackName = fm.getBackStackEntryAt(entry).getName();
                    Log.i("BC", "stackEntry" + entry);
                }
                if (stackName == "Fragment1"){
                    mDrawerList.setItemChecked(0, true);
                } else if (stackName == "Fragment2") {
                    mDrawerList.setItemChecked(1, true);
                }

            });
查看更多
登录 后发表回答