How to set shared checkable behavior across all groups in NavigationView?
Actually, you don't need separate parallel groups for separators. You can have everything in one group and place submenus (have titles) or subgroups (no title) in it. There will be separators for those submenus and subgroups. This way the checkable behavior works without a workaround. (Fyi: This is on Design Support Lib 23.1.1)
<group
android:id="@+id/drawer_group"
android:checkableBehavior="single">
<item
android:id="@+id/nav_1"
android:title="Menu1" />
<item
android:id="@+id/nav_2"
android:title="Menu2" />
<item
android:id="@+id/nav_3"
android:title="Menu3" />
<item
android:id="@+id/nav_4"
android:title="Menu4" />
<item
android:id="@+id/drawer_submenu"
android:title="Subheader">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_sub1_1"
android:title="Menu_Sub1_1" />
<item
android:id="@+id/nav_sub1_2"
android:title="Menu_Sub1_2" />
</group>
</menu>
</item>
<group android:id="@+id/drawer_subgroup">
<item
android:id="@+id/nav_subgroup_item"
android:title="Menu_Sub2_2" />
</group>
</group>
In code, I simply do the following and single checking works as expected:
@Override
public boolean onNavigationItemSelected(MenuItem item) {
mNavigationView.setCheckedItem(item.getItemId());
...
}
Here's the solution.
Step 1: Remove
android:checkableBehavior="single"
from both groups.
Step 2: Add the following logic to the listener:
mUiNavigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setCheckable(true);
menuItem.setChecked(true);
if (mPreviousMenuItem != null) {
mPreviousMenuItem.setChecked(false);
}
mPreviousMenuItem = menuItem;
//...
changeCurrentFragment(...);
return true;
}
});
Note: instead of calling menuItem.setCheckable(true)
you can set android:checkable="true"
for each item in XML.
@Moinkhan's solution should work as well (thanks, upvoted), but I didn't want to loop through menu's items each time a new position is selected.