Updating the navigation box (using DrawerLayout) when you click the back button

I am developing an Android application with a navigation box. Suppose I move through fragments and go from Fragment 1 to Fragment 2 . Everything works fine, but when I am in Fragment 2 (which is loaded from the navigation drawer) and presses the system back button, although I get the previous snippet (I use addToBackStack ), the navigation drawer is not updated, and the Fragment 2 cell is highlighted. What should I do to fix this?

+4
source share
2 answers

Found a solution:

Added tag in each addToBackStack . So the code, if I call addToBackStack , looks like this:

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

whenever I push each fragment on the stack. Then I cancel the pressed back button:

 @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
source

Question: 2 years and @alecnash answer works. But, in my opinion, it incorrectly assigns the onBackPressed() method ... and for the later googler:

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

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

Source: https://habr.com/ru/post/1488056/


All Articles