Reputation: 105
So i have a navigation menu , who's NavigationView is such :-
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Menu m = navigationView.getMenu();
SubMenu subMenu = m.addSubMenu("Top Playlists");
subMenu.add("Foo");
subMenu.add("Bar");
subMenu.add("Kamehameha");
MenuItem mi = m.getItem(m.size()-1);
mi.setTitle(mi.getTitle());
So what i'm doing here is i'm dynamically adding Foo , bar , etc as menu items. However , when i click them , they do not get highlighted as the other menu items that have been explicitly declared in the menu layout.
Menu layout :
<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>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_menu_share"
android:title="Share" />
<item
android:id="@+id/nav_send"
android:icon="@drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
My onNavigationItemSelected :
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
Now when i select , foo , bar , etc , they do get selected , however their text color doesn't change. How can i rectify this? Also , inside onNavigationItemSelected(MenuItem item) , how do i assign behaviour to these dynamically added items , who don't have an item id?
Upvotes: 0
Views: 204
Reputation: 17119
I had a similer problem and I fixed that by calling the method setCheckedItem(int idRes)
of NavigationView
. Do something like
@Override
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
// Handle navigation view item clicks here.
int id = item.getItemId();
// Set the item as checked.
navigationView.setCheckedItem(id);
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
Upvotes: 0