3

I'm trying to dynamically set the title of my menu.

Retrieving and setting it as such:

ItemView menuTitle = ((ItemView) findViewById(R.id.menu_filter));
menuTitle.setTitle("TITLE_HERE");

works just fine so long as it's in the onOptionsItemSelected(MenuItem item) method.

I haven't been able to find a way to set this from the onPrepareOptionsMenu or onCreateOptionsMenu methods as findViewById returns null (even after inflating the menu).

Oddly enough there doesn't seem to be anything in the documentation for accomplishing this and google searches haven't turned up much for such a seemingly simple problem.

Ani
  • 1,655
  • 3
  • 23
  • 37
user2884265
  • 113
  • 1
  • 1
  • 8

4 Answers4

5

I must have just derped and not realized that there is a function for Menu called findItem...

menu.findItem(R.id.MENU_TITLE).setTitle("MY TITLE");
user2884265
  • 113
  • 1
  • 1
  • 8
3

To dynamically set menu title, you'd do this in onCreateOptionsMenu:

public boolean onCreateOptionsMenu(Menu menu) 
{
      menu.add(Menu.NONE, MyActivity.MENU_ID, 0, "Your Title").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    return (true);
}

and as conditions change (i.e. as your title needs to change), call

invalidateOptionsMenu();

on your activity, which will call onCreateOptionsMenu and set the new title.

CSmith
  • 13,318
  • 3
  • 39
  • 42
2

Just use :

        getSupportActionBar().setTitle("YOUR TITLE HERE");

Inside on create, after initializing ui or viewbinding or databinding.

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
1

I am changing the title of the menu from onPrepareOptionMenu something like the below code. This is the code from my fragment, I think this should also work on the activity.

 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.menu_profile, menu)
    super.onCreateOptionsMenu(menu, inflater)
}

override fun onPrepareOptionsMenu(menu: Menu) {
    super.onPrepareOptionsMenu(menu)
    if (count == 1) {
        menu.findItem(R.id.screen_count).title = "1/3"
    } else {
        menu.findItem(R.id.screen_count).title = "xyz/3"
    }
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        R.id.ic_edit -> {
            // handle click event here
        }
    }
    return super.onOptionsItemSelected(item)
}
Nabin Khatiwada
  • 478
  • 5
  • 15