androidexceptionandroid-actionbarandroid-menu

Android menu item visibility change in runtime


I am trying to hide an action bar menu item for a certain period of time while a task is being performed in the background of the running activity.

First in the activity's onPrepareOptionsMenu method, I retrieve the MenuItem instance as a field.

public void onPrepareOptionsMenu(final Menu menu) {
    super.onPrepareOptionsMenu(menu);
    // Retrieve and show the contextual settings menu item
    mContextualSettings = menu.findItem(R.id.item_menu_contextual_settings);
    mContextualSettings.setVisible(true);
}

Later I use that field to make it invisible and visible again(by using the setVisible method).

I was wondering if this is a good approach or should I somehow use the invalidateOptionsMenu() to make it visible again? Can I ran into null pointer exceptions?

Thanks.


Solution

  • I retrieve the MenuItem instance as a field. [...] I was wondering if this is a good approach or should I somehow use the invalidateOptionsMenu() to make it visible again?

    This is not the recommended way to do what you're trying. You're better off using supportInvalidateOptionsMenu() to trigger onPrepareOptionsMenu() and a boolean field or method to check to then set the visibility of the item directly.

    Can I ran into null pointer exceptions?

    In recent versions of Android, it is possible for onPrepareOptionsMenu() to be called before the Menu has been inflated via onCreateOptionsMenu(). So you should always perform a null check on the results of menu.findItem(), or otherwise protect against this scenario (perhaps by checking if menu.getSize() > 0).