5

I have a menu with all items' showAsAction set to ifRoom. Now I want to get the exact position (x,y) of the center of any of these menu items.

I first thought of getting this information from the underlying views, but I don't know how to reliably access the view of a specific menu item.

In onCreateOptionsMenu:

MenuItem someItem = menu.findItem(R.id.some_action); // someItem.getX(); // someItem.getY(); 

I'd expect these coordinates to be relative to the application's Toolbar. In this case I also need access to someItem.get{Width,Height}() to calculate the center coordinates.

An example menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:title="@string/action_search" android:icon="@drawable/ic_search" app:actionViewClass="android.support.v7.widget.SearchView" app:showAsAction="ifRoom|collapseActionView" /> <item android:id="@+id/action_example" android:title="@string/action_example" android:icon="@drawable/ic_example" app:showAsAction="ifRoom" /> </menu> 
1

1 Answer 1

4

The solution is to use the underlying activity to find the instanciated view.

View menuItemView = getActivity().findViewById(R.id.action_search); 

Then the position can be extracted relative to the toolbar by using View.getLocationInWindow(intArr), which returns (x,y) relative to the view's window.

int[] itemWindowLocation = new int[2]; menuItemView.getLocationInWindow(itemWindowLocation); int[] toolbarWindowLocation = new int[2]; toolbar.getLocationInWindow(toolbarWindowLocation); int itemX = itemWindowLocation[0] - toolbarWindowLocation[0]; int itemY = itemWindowLocation[1] - toolbarWindowLocation[1]; int centerX = itemX + menuItemView.getWidth() / 2; int centerY = itemY + menuItemView.getHeight() / 2; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.