I know it's possible to highlight a navigation view item by calling setCheckedItem()
or return true value in onNavigationItemSelected
to display the item as the selected item, but How can I uncheck the checked items of a navigation view?
This will uncheck the items:
int size = mNavigationView.getMenu().size();
for (int i = 0; i < size; i++) {
mNavigationView.getMenu().getItem(i).setCheckable(false);
}
I saw @arsent solution and gave it a try, and it will indeed do what you want, which is to unselect all the items... but, I was having an issue in the following scenario:
NavigationView#setCheckedItem
)NavigationView#setCheckedItem
)In this scenario, item 1 will not be marked as checked. That's because internally the navigation view keeps track of the previously selected item set in step 1, which doesn't change in step 2, and it just skips step 3 because the previously selected item is the same as the one we're selecting now.
My suggestion (and an alternative solution) to avoid this is just having a dummy invisible item and use NavigationView#setCheckedItem
to select that item whenever you want to unselect all, like so
<item
android:id="@+id/menu_none"
android:title=""
android:visible="false"/>
To unselect all just do
mNavigationView.setCheckedItem(R.id.menu_none);
To uncheck all MenuItems
including SubMenu
items you have to use recursion -
private void unCheckAllMenuItems(@NonNull final Menu menu) {
int size = menu.size();
for (int i = 0; i < size; i++) {
final MenuItem item = menu.getItem(i);
if(item.hasSubMenu()) {
// Un check sub menu items
unCheckAllMenuItems(item.getSubMenu());
} else {
item.setChecked(false);
}
}
}
Call above method for unchecking all items, like below -
unCheckAllMenuItems(navigationView.getMenu());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With