Search code examples
androidandroid-actionbar-compat

Can I get the position of the overflow menu and any other menu in the Action Bar


I have a ActionBar setup in my AppCompatActivity and I would very much like to be ablt to get the position of the menu items and the overflow menu, so that I can have a tool tip pointing to any item in the ActionBar. I have tried many ways now, and I do have a way to get hold on the ActionBar and the Toolbar, but it seems that any views in there always has a left of zero and so on. I have created a tool tip component that is a PopupWindow, and I can position this over the ActionBar no problem, but I can not figure out how to get the correct position of the menu items. Is there a way to this?

Thank you
Søren


Solution

  • You are probably always getting a zero top and left position because you are trying to read the position before the view is laid out.

    To get the position when the views are measured and layout, you have to ViewTreeObserver.

    In your activity's onCreate(), you can do something like this :

        toolbar.getViewTreeObserver().addOnPreDrawListener(
            new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    toolbar.getViewTreeObserver().removeOnPreDrawListener(this);
    
                    // here you can get the real position of each menu item and position your Popup
                    return true;
                }
            });