NavigationDrawer / NavigationView check menu subitems

I needed a  NavigationDrawer in an app I was building and decided to try the “new” Material Design Support Library and use a NavigationView to implement it. Using Android Studio version 2.1, I started the app by selecting the Navigation View Activity.

Choosing the Navigation View Activity creates a project with a number of default files related to the NavigationView :

  • activity_main.xml which defines the DrawerLayout and its NavigationView
  • nav_header_main.xml which defines the NavigationView header
  • activity_main_drawer.xml which defines the NavigationView menu

and produces an example NavigationView that has a parent menu with four items and a submenu with two items. The main menu is set to automatically persist the selection by using

<group android:checkableBehavior="single">

With the submenu items acting as “action” selections that do not retain their state since the CheckableBehaviour was not set for the submenu.

With my application, I have a main menu with a one static submenu defined in the xml file and then a second submenu generated dynamically in code. Even though there are two submenus, I still want only one item in the NavigationView selected and highlighted at a time. Since the CheckableBehaviour does not extend across <menu> settings, I had to manually force the the highlight.

Each item needed to have checkable set to true.  Either in the xml:

android:checkable="true"

or in code:

.setCheckable(true)

Then after managing the new item selected in

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    int menuId = menuItem.getItemId();

I initially added the following which, unfortunately, did not work…

menuItem.setChecked(true);

but then I tried the following which did work to highlight the selected menu item in the NavigationView:

// Highlight the selected item in the NavigationView
NavigationView navigationView = 
        (NavigationView) findViewById(R.id.nav_view);
navigationView.setCheckedItem(menuId);
This entry was posted in Android App Development. Bookmark the permalink.