Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current location of an ActionBar MenuItem?

Tags:

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?

like image 481
Pieter888 Avatar asked May 01 '12 12:05

Pieter888


People also ask

What is MenuItem in Android?

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 .

What is ActionBar in Android?

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.

Which method is used to create menu items on ActionBar?

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.

How do I hide a menu item in the ActionBar?

You can set a flag/condition. Call invalidateOptionsMenu() when you want to hide the option. This will call onCreateOptionsMenu() .


1 Answers

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.

like image 182
BoD Avatar answered Sep 30 '22 19:09

BoD