android – Initially Hidden MenuItem Not Shown When setVisible(true) is Called-ThrowExceptions

Exception or error:

I have a basic problem where an initially hidden MenuItem is unable to be toggled to visible. As a caveat, I am using ActionBarSherlock, but I wanted to see if anyone knew if this was a known issue of Android or I am doing something terrible before investigating whether this is an issue inside of ABS. Code as follows:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.menu_xml, menu);

    mMenuItem = menu.findItem(R.id.menu_item);
    mMenuItem.setVisible(false);

    return true;
}

// Somewhere elsewhere
// MenuItem is never visible after this line is executed
mMenuItem.setVisible(true);

I have also tried to move the mMenuItem assignment and visibility into a call to onPrepareOptionsMenu but the same behavior is shown.

Thanks!

How to solve:

The problem is you are not telling Android that it needs to update the menu. This drove me nuts for the last hour until I figured out a solution. I don’t think it’s as apparent on pre-HC because menu items aren’t always visible on the screen like they are in HC+.

On your activity, simply call:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
this.invalidateOptionsMenu();
}

That will trigger a call to the onCreateOptionsMenu() event again, so if you’re setting the visibility in that function for initialization you’ll need to take into account then if you want the option to show or not.

###

I had the same problem and I found out that setVisible(true) works when there is at least another MenuItem visible. I hope this can be helpful to someone.

###

I understand this is old question.
But I’ve solved it by placing inside onPrepareOptionMenu() {...}

private boolean mShowVisible=false;

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

     menu.findItem(R.id.menu_item).setVisible(mShowVisible);

     return super.onPrepareOptionsMenu(menu);
}

whenever you want to set visible or not just call it as:

mShowVisible = true; // or false
invalidateOptionMenu();

###

I found that using a view’s post(Runnable) method to setVisible does the trick, so something like…

view.post(new Runnable() {

                @Override
                public void run() {
                    menu.findItem(id).setVisible(true);
                }

            });

Leave a Reply

Your email address will not be published. Required fields are marked *