-2

I'm using the NavigationView drawer in my app. I'm trying go back to the previous Fragment if the user press back button. This code works well:

@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();        
    Fragment fr = fm.findFragmentById(R.id.flContent);

    if (fm.getBackStackEntryCount() > 0 ) {
        fm.popBackStackImmediate();
    }
    else {
        finish();
    }        
}

But my NavigationView doesn't change. How can I update the NavigationView state (check the correct fragment, change title, and so on), so it can reflect the changes in my app?

aseolin
  • 1,184
  • 3
  • 17
  • 35

2 Answers2

0

You should implement Back Navigation using addToBackStack method. Take a look at this.

user3641702
  • 393
  • 1
  • 5
  • 18
  • This answers only the question when to update. I could also use onBackPressed(). The main question is which position should be highlighted in the drawer? – aseolin Jul 27 '15 at 13:53
  • check the first answer [link](http://stackoverflow.com/questions/18305945/how-to-resume-fragment-from-backstack-if-exists) – user3641702 Jul 27 '15 at 14:25
0

I created a workaround: When drawer is created or menuItem is clicked, I'm storing the current menuItem:

private void setupDrawerContent(NavigationView navigationView) {
    // Storing "home" menuItem when app starts
    storedMenuItem = navigationView.getMenu().getItem(0);

    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);

                    // Storing menuItem when another item is selected
                    storedMenuItem = menuItem;

                    return true;
                }
            });
}

So in my onBackPressed method I'm doing this:

  @Override
  public void onBackPressed() {
    selectDrawerItem(storedMenuItem);
  }

No changes on selectDrawerItem (I used this code)

I don't know if it's a good solution, but it's working very well.

aseolin
  • 1,184
  • 3
  • 17
  • 35