change MenuItem visibility when clicked

六眼飞鱼酱① 提交于 2019-12-01 21:25:09

问题


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.


回答1:


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().




回答2:


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;
      }


来源:https://stackoverflow.com/questions/14018224/change-menuitem-visibility-when-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!