问题
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