András Ferencz András Ferencz - 5 months ago 61
Android Question

"Back button" using getSupportActionbar and appcompat v7 toolbar

I'm using the new toolbar from the Appcompat V7 library and I'm making an application with navigation drawer and with fragments.

In some fragments I don't want to show the hamburger icon but the arrow instead... That is fine I did this in this way:

mDrawerToggle.setDrawerIndicatorEnabled(false);

mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);


My question is that: How or where i need to set up the home button lisener or what i need to listen for the "back" button ?
I want to call the main backpressed method and to set back the navigation drawer icon with the hamburger icon..

Answer

You can do it like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  
    toolbar = (Toolbar)findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    setUpNavigationDrawer();

    getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}

Define the onBackSTackChangedListener:

private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
   @Override
   public void onBackStackChanged() {
       setNavIcon();
   };
}

Set the icon according to your fragment's backstack:

protected void setNavIcon() {
    int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
    drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}

Detect when the drawer icon is pressed:

public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
      case x:
         return true;
      default:
         return false;
    }
}

And handle the up button:

public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

This works for me. Good luck.