Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Created September 20, 2018 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imandaliya/063bb187f81690b5cb874f4241741d52 to your computer and use it in GitHub Desktop.
Save imandaliya/063bb187f81690b5cb874f4241741d52 to your computer and use it in GitHub Desktop.
// This method allow to handle Drawer and back functionality with state.
public class ToolbarToggleUtils {
public static void enableViews(boolean enable) {
// To keep states of ActionBar and ActionBarDrawerToggle synchronized,
// when you enable on one, you disable on the other.
// And as you may notice, the order for this operation is disable first, then enable - VERY VERY IMPORTANT.
if(enable) {
//You may not want to open the drawer on swipe from the left in this case
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Remove hamburger
mDrawerToggle.setDrawerIndicatorEnabled(false);
// Show back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// when DrawerToggle is disabled i.e. setDrawerIndicatorEnabled(false), navigation icon
// clicks are disabled i.e. the UP button will not work.
// We need to add a listener, as in below, so DrawerToggle will forward
// click events to this listener.
if(!mToolBarNavigationListenerIsRegistered) {
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Doesn't have to be onBackPressed
onBackPressed();
}
});
mToolBarNavigationListenerIsRegistered = true;
}
} else {
//You must regain the power of swipe for the drawer.
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
// Remove back button
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Show hamburger
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Remove the/any drawer toggle listener
mDrawerToggle.setToolbarNavigationClickListener(null);
mToolBarNavigationListenerIsRegistered = false;
}
// So, one may think "Hmm why not simplify to:
// .....
// getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
// mDrawer.setDrawerIndicatorEnabled(!enable);
// ......
// To re-iterate, the order in which you enable and disable views IS important #dontSimplify.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment