Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

I'm trying to change the title of a menu item from outside of the onOptionsItemSelected(MenuItem item) method.

I already do the following;

public boolean onOptionsItemSelected(MenuItem item) {

  try {

    switch(item.getItemId()) {

      case R.id.bedSwitch:

        if(item.getTitle().equals("Set to 'In bed'")) {

          item.setTitle("Set to 'Out of bed'");

          inBed = false;

        } else {

          item.setTitle("Set to 'In bed'");

          inBed = true;

        }

        break;

    }

  } catch(Exception e) {

    Log.i("Sleep Recorder", e.toString());

  }

  return true;

}

however I'd like to be able to modify the title of a particular menu item outside of this method.

1 Answer

0 votes
by (46k points)

I would recommend keeping a reference within the project to the Menu object you hold in onCreateOptionsMenu and then using that to recover the MenuItem that requires the change as and when you need it. For instance, you could do something along the lines of the accompanying:

public class YourActivity extends Activity {

  private Menu menu;

  private String inBedMenuTitle = "Set to 'In bed'";

  private String outOfBedMenuTitle = "Set to 'Out of bed'";

  private boolean inBed = false;

  @Override

  public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);

    // Create your menu...

    this.menu = menu;

    return true;

  }

  private void updateMenuTitles() {

    MenuItem bedMenuItem = menu.findItem(R.id.bedSwitch);

    if (inBed) {

      bedMenuItem.setTitle(outOfBedMenuTitle);

    } else {

      bedMenuItem.setTitle(inBedMenuTitle);

    }

  }

}

Alternatively, you can revoke onPrepareOptionsMenu to update the menu items every time the menu is displayed.

Related questions

0 votes
1 answer
asked Sep 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...