Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initially Hidden MenuItem Not Shown When setVisible(true) is Called

Tags:

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!

like image 990
PolandSpring Avatar asked Jul 10 '12 21:07

PolandSpring


2 Answers

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.

like image 59
Tony Maro Avatar answered Oct 18 '22 23:10

Tony Maro


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.

like image 34
Alessandro Roaro Avatar answered Oct 19 '22 00:10

Alessandro Roaro