I'm trying to implement a Navigation Drawer that hides the menu items in the ActionBar whenever the drawer is opened.
I am following google's documentation, however their code does not produce the expected behavior.
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Using this code, the menu items are hidden when the drawer becomes completely opened , and shown when the drawer becomes completely closed.
However, the Gmail app behaves differently. The menu items are hidden as soon as the drawer opens by any amount. This is the behavior I want. Does anyone know how to achieve this?
Thanks!
Have you tried this:
invalidateOptionsMenu()
whenever you toggle the nav drawer, by measuring the sliding offset.Iterate over each menu item in
onPrepareOptionsMenu(Menu menu)
and hide it.Detecting how much the nav drawer has slided:
Note:
shouldGoInvisible
is class field.I have a better solution for this question:
I'd half agree with Nikola but it's sufficient just to update the icons when the drawer state has
Create a global variable to keep track of the drawer state:
Set a new DrawerListener:
Update the menu visibility:
If you want to override action bar as soon as drawer enters screen and restore action bar the moment drawer is no longer visible (exactly how Gmail behaves as of March 20, 2014) you can use the following code:
Modify
restoreActionBar()
andoverrideActionBar()
methods acording to your needs.There is no need to distinguish between swipes and home button and no need to measure swipe lengths.
Variation
If you don't want to reference the drawer list view use the following code instead:
You may want to use
GravityCompat.END
instead depending on what you specified in XML layout.Edit - concerning actions
The above example does not hide action bar items relevant to content below the navigation drawer. To do so or show different set of icons when drawer is visible you have to keep track of whether the drawer is opened or closed manually.
In addition to the above code declare
private boolean mDrawerVisible = false
with proper save/restore state handling. Then modifymDrawerToggle
inner methods as follows:Finally in
onCreateOptionsMenu
inflate different menu resource or inonPrepareOptionsMenu
show/hide different actions based on the value ofmDrawerVisible
.I took the answer by @Laurence Dawson and simplified it a bit. This solution does not require any class members to be used.
Execute this code during
onCreate()
:And override this method:
Few notes:
layout_gravity
set tostart
in XML.I have different code but the same solution:
and