I want to show a little info label underneath a MenuItem
in the app's ActionBar
. To position this correctly I need to know the x-position of a MenuItem
.
Google brought me no useful results so far.
Is it even possible?
android.view.MenuItem. Interface for direct access to a previously created menu item. An Item is returned by calling one of the Menu. add(int) methods. For a feature set of specific menu types, see Menu .
Android ActionBar is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items which become visible when the user clicks the “menu” button.
The Android tooling automatically creates a reference to menu item entries in the R file, so that the menu resource can be accessed. An activity adds entries to the action bar in its onCreateOptionsMenu() method. The showAsAction attribute allows you to define how the action is displayed.
You can set a flag/condition. Call invalidateOptionsMenu() when you want to hide the option. This will call onCreateOptionsMenu() .
I found another way to get a hook on an action bar button, which may be a bit simpler than the accepted solution. You can simply call findViewById
, with the id of the menu item!
Now the hard part is when can you call this? In onCreate
and onResume
, it is too early. Well one way to do this is to use the ViewTreeObserver
of the window:
final ViewTreeObserver viewTreeObserver = getWindow().getDecorView().getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { View menuButton = findViewById(R.id.menu_refresh); // This could be called when the button is not there yet, so we must test for null if (menuButton != null) { // Found it! Do what you need with the button int[] location = new int[2]; menuButton.getLocationInWindow(location); Log.d(TAG, "x=" + location[0] + " y=" + location[1]); // Now you can get rid of this listener viewTreeObserver.removeGlobalOnLayoutListener(this); } } });
This goes in onCreate
.
Note: this was tested on a project using ActionBarSherlock, so it is possible that it doesn't work with a 'real' action bar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With