Created
September 20, 2018 10:36
-
-
Save imandaliya/063bb187f81690b5cb874f4241741d52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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