I followed the Android Developer documentation to create a navigation drawer.
Then I wanted to add 2 groups of menu items. One for user created lists, the other for labels. Since I couldn't directly set titles to groups, I followed the tutorial HERE and wrapped groups in tags.
My XML menu looks like this:
In onCreate I find the NavigationView using its id, then get its menu, get the first by its id, get the item's SubMenu and add MenuItems:
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem item = menu.findItem(R.id.item_lists);
SubMenu sbLists = item.getSubMenu();
sbLists.add(0, 0, 0, "Android").setIcon(R.drawable.ic_android);
sbLists.add(0, 1, 0, "iOS").setIcon(R.drawable.ic_ios);
And:
navigationView.setNavigationItemSelectedListener(
menuItem -> {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
When I click the items added in XML, the drawer closes and if I open it again I can see the item is selected. However, with the items added in onCreate, this is what I see after I re-open the drawer:
Clicking this one
It's gone
I've tried searching on Stack Overflow and found only one question with the same problem Navigation item's title disappeared when clicked , however, the solution is to set the item text color to black. That doesn't fix the item not being selected problem and doesn't fix the icon disappearing either.
Please let me know what I'm doing incorrectly, thank you!
Edit: Here's what my Theme looks like in styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionModeOverlay">true</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="iconColor">@color/icons_light</item>
<item name="toolbarIconColor">@color/icons_light</item>
<item name="android:textColorPrimary">@color/primary_text</item>
</style>