Navigation drawer: How do I set the selected item at startup?
Use the code below:
navigationView.getMenu().getItem(0).setChecked(true);
Call this method after you call setNavDrawer();
The getItem(int index)
method gets the MenuItem
then you can call the setChecked(true);
on that MenuItem
, all you are left to do is to find out which element index does the default have, and replace the 0 with that index.
You can select(highlight) the item by calling
onNavigationItemSelected(navigationView.getMenu().getItem(0));
Here is a reference link: http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html
EDIT Did not work on nexus 4, support library revision 24.0.0. I recommend use
navigationView.setCheckedItem(R.id.nav_item);
answered by @kingston below.
For me both these methods didn't work:
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(id);
Try this one, it works for me.
onNavigationItemSelected(navigationView.getMenu().findItem(R.id.nav_profile));
You can also call:
navigationView.setCheckedItem(id);
This method was introduced in API 23.0.0
Example
<?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:ignore="UnusedIds">
<group
android:id="@+id/group"
android:checkableBehavior="single">
<item
android:id="@+id/menu_nav_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/menu_nav_home" />
</group>
</menu>
Note: android:checkableBehavior="single"
See also this