Updating the Navigation Drawer (with DrawerLayout) when back button is pressed

狂风中的少年 提交于 2019-12-06 04:13:14

问题


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?


回答1:


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



回答2:


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

            });


来源:https://stackoverflow.com/questions/17295946/updating-the-navigation-drawer-with-drawerlayout-when-back-button-is-pressed

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