I have an app with a navigation drawer and 4 navigation items (Fragments). In one of the Fragments, I have a tab layout set up with a view pager (3 more Fragments).
From one of these inner fragments, I want to disable/enable the navigation drawer dynamically. Basically, on a button press, I want to restrict access to the navigation drawer (and the re-enable on pressing it again).
How would I do it?
I tried accessing the DrawerLayout
of the parent activity from this inner fragment. But I see no methods to enable/disable the navigation drawer.
The way I've added the drawer to my main Activity:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
(and of course I've added toggle.syncState()
from within the onPostCreate
method.
A clean way to do this is to create an
interface
that theActivity
implements, through which theFragment
can call a method local to theActivity
that handles the drawer lock and toggle button states. For example:In the
Activity
'sinterface
method, we simply figure the lock mode constant for theDrawerLayout#setDrawerLockMode()
call, and callsetDrawerIndicatorEnabled()
on theActionBarDrawerToggle
.In the
Fragment
, we merely need to cast the hostingActivity
to theinterface
, and call thesetDrawerEnabled()
method accordingly. For example, to lock the drawer shut:NB: Since version 23.2.0 of the v7 appcompat support library,
ActionBarDrawerToggle
respects theDrawerLayout
's lock mode, and will not toggle the drawer state if it is locked. This means that it is not strictly necessary to usesetDrawerIndicatorEnabled()
, though it might be desirable to still do so in order to provide the user a visual indication that the toggle is disabled.