0 votes
1 view
in Java by (8.5k 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 (41.5k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...