scarhand
scarhand

Reputation: 4337

change MenuItem visibility when clicked

I'm trying to hide one MenuItem and make another visible when the first is selected.

The ID's for each are:

pencil: R.id.button_routines_edit
check mark: R.id.button_routines_edit_done

Here the relevant code:

  private boolean isEditing = false;

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {   
      // Handle item selection
      switch (item.getItemId()) {
      case R.id.button_routines_edit:
            // hide pencil icon, show checkmark
            isEditing = true;
        return true;
      case R.id.button_routines_edit_done:
            // show pencil icon, done editing
            isEditing = false;
        return true;
      default:
          return super.onOptionsItemSelected(item);
      }

  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
      super.onPrepareOptionsMenu(menu);
      // hide pencil when editing and show check mark
      menu.findItem(R.id.button_routines_edit).setVisible(!isEditing);
      menu.findItem(R.id.button_routines_edit_done).setVisible(isEditing);
      return true;
  }

My problem is: The Options Menu doesn't redraw the items when they're selected. In other words, the first isn't hidden and the second isn't shown.

Upvotes: 4

Views: 3584

Answers (2)

adneal
adneal

Reputation: 30804

All you need to do is call invalidateOptionsMenu().

invalidateOptionsMenu() is only available in API 11+, unless you're using ActionBarSherlock.

You're having this problem because your MenuItems are show in the ActionBar, basically. If you place them in the overflow menu, you won't need to call invalidateOptionsMenu().

Upvotes: 5

No_Rulz
No_Rulz

Reputation: 2719

Try this, It must hide the Menu Item

public boolean onCreateOptionsMenu(Menu menu){

          menu.getItem(R.id.button_routines_edit).setVisible(!isEditing);
          menu.getItem(R.id.button_routines_edit_done).setVisible(isEditing);
          return true;
      }

Upvotes: -1

Related Questions