Home > Enterprise >  How can I change MenuItem's title programatically inside NavigationView?
How can I change MenuItem's title programatically inside NavigationView?

Time:04-07

I successfully implemented in my app a "side menu" with NavigationView and creating a custom ActionBar, following the instructions within enter image description here

That's great, it works... it opens by "hamburger" button in ActionBar and by sliding finger left to right; I can attach functionality to those options. But, I'd like to change options title dinamically, by Java. About that, I found some other StackOverflow question and tried implementing the solution in the answer. The result was... unexpected, but curious:

I override onPrepareOptionsMenu in MainActivity:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    menu.clear();
    getMenuInflater().inflate(R.menu.main_menu, menu);
    MenuItem option3 = menu.findItem(R.id.nav_option3);
    option3.setTitle("Option3 -> "   option3_cnt   " elements");
    MenuItem option4 = menu.findItem(R.id.nav_option4);
    option4.setTitle("Option4 -> "   option4_cnt   " elements");

    return super.onPrepareOptionsMenu(menu);
}

What this actually did, was creating a copy of the NavigationView menu, but in a "three-dot button" at the right side of ActionBar (that button wasn't there before implementing onPrepareOptionsMenu, BTW). And yes, it shows the counters; but the idea was doing exactly that thing, but with the "side menu" of the NavigationView, instead of that old-fashioned "options menu". How can I achieve that?

By the way, MenuItems have a XML structure like this within main_menu.xml:

<item
    android:id="@ id/nav_option3"
    android:icon="@drawable/ic_launcher_foreground"
    android:title="Option3" />
<item
    android:id="@ id/nav_option4"
    android:icon="@drawable/ic_launcher_foreground"
    android:title="Option4" />

I'd like, perhaps, to add more elements to the MenuItems themselves; so I could place the counter in some kind of "custom layout" attached to the MenuItem or something like that... but for now, I conform with attaching the count to the title itself.

CodePudding user response:

You can just get the menu from NavigationView & do the findItem to get access to MenuItem which then you can use to setTitle.

Example:

    // your navigationView
    NavigationView navigationView = findViewById(R.id.navigation_view);
    
    // item you want to change, choose your id here
    MenuItem menuItem = navigationView.getMenu().findItem(R.id.nav_gallery);
    menuItem.setTitle("Changed at runtime");
  • Related