I make this menu in NavigationView :

 <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_manage" android:icon="@drawable/ic_menu_manage" android:title="Tools" /> </group> <item android:title="Communicate"> <menu> <group android:checkableBehavior="single"> <item android:id="@+id/nav_share" android:icon="@drawable/ic_menu_share" android:title="Share" android:checked="true"/> <item android:id="@+id/nav_send" android:icon="@drawable/ic_menu_send" android:title="Send" /> </group> </menu> </item> </menu> 

I need to select the Share element at the start, for this I have registered

 android:checked="true" 

When starting, get the following picture

When I click on the Send element, it shows 2 selected items:

How to fix this error?

  • In the code when clicking on an item, register navigationView.setCheckedItem(R.id.itemID); Should work ... - DevOma 10:21 pm
  • the first element you have registered in the markup to be selected, so it is always selected now - pavlofff
  • @DevOma thanks, it worked. I think your decision is the best. - Tim

1 answer 1

Good night, just mark the desired menu item with the selected program. Just do not forget, please remove the line android: checked = "true" in the markup.

 NavigationView navigationView = (NavigationView) findViewById(R.id.main_navigation_view); navigationView.getMenu().getItem(5).setChecked(true); 

After that, if you properly handle clicks in the navigationView using the NavigationItemSelectedListener, everything should work as it should.

  • It is possible and so, only the 2nd line is a bit incorrect, because we have the 5th element "Communicate", has a submenu. It will be correct like this: navigationView.getMenu (). GetItem (4). GetSubMenu (). GetItem (0) .setChecked (true); And then handle clicks in the NavigationItemSelectedListener. But it's easier to do, as @DevOma said, to register only navigationView.setCheckedItem (R.id.itemID); - Tim