Reputation: 1433
I am moving some menu items from the options menu to the navigation menu. My app uses a NavigationView that is populated by a menu as described at https://developer.android.com/reference/android/support/design/widget/NavigationView.html
One of the items calls webView.goBack()
on the WebView
in the main activity. When it was placed in the options menu, it was only enabled if webView.canGoBack()
. Otherwise, it was disabled (grayed out). To accomplish this, onPrepareOptionsMenu()
included the command:
back.setEnabled(webView.canGoBack());
As onPrepareOptionsMenu()
is called every time the options menu is about to be displayed, this would update the status of the menu item to correctly reflect the state of the WebView
.
However, I have not been able to replicate this behavior with the NavigationView. Is there a method or class similar to onPrepareOptionsMenu()
that is called each time the NavigationView is prepared?
PS. Other people who have addressed similar questions have always referred to using a ListView, which was an older method of populating a navigation drawer. This question specifically relates to using a NavigationView with a menu.
Upvotes: 2
Views: 951
Reputation: 1433
The answer to this question is to add a DrawerListener
and override onDrawerStateChanged
.
// Create the navigation drawer.
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// The `DrawerTitle` identifies the drawer in accessibility mode.
drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
// Listen for touches on the navigation menu.
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
// Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so item 1 and 2 and the second and third items in the menu.
final Menu navigationMenu = navigationView.getMenu();
final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
// The `DrawerListener` allows us to update the Navigation Menu.
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
}
@Override
public void onDrawerClosed(View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
// Update the back and forward menu items every time the drawer opens.
navigationBackMenuItem.setEnabled(webView.canGoBack());
navigationForwardMenuItem.setEnabled(webView.canGoForward());
}
});
Upvotes: 2
Reputation: 317760
NavigationView exposes its underlying Menu with getMenu(). You can use that to find menu items and make changes to them.
Upvotes: 0