Change MenuItem visibility when pressed

I try to hide one MenuItem and make the other visible when the first one is selected.

Identifier for each of them:

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

Here is 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: The Options menu does not redraw items when they are selected. In other words, the first is not hidden, and the second is not shown.

+4
source share
2 answers

All you have to do is call invalidateOptionsMenu() .

invalidateOptionsMenu () is only available in API 11+ if you are not using ActionBarSherlock .

You are having this problem because your MenuItems displayed in the ActionBar basically. If you put them in the overflow menu, you will not need to call invalidateOptionsMenu() .

+5
source

Try this, it should 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; } 
-1
source

All Articles