In the tutorial of my application, I'd like to be able to point to particular icons in the action bar, like e.g. with the yellow arrow pointing at the bulb in the picture below:
Here is the XML code for the menu items shown in the picture:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="@+id/AbErase"
android:icon="@android:drawable/ic_delete"
android:orderInCategory="10"
android:title="@string/Erase"
android:tooltipText="@string/Erase"
app:showAsAction="ifRoom|collapseActionView"
/>
<item android:id="@+id/AbImmediateImplementation"
android:title="@string/ImmediateImplementation"
android:checkable="true"
android:orderInCategory="20"
app:showAsAction="never|withText"
android:enabled="true" />
<item android:id="@+id/AbSuggest"
android:title="@string/Suggest"
android:tooltipText="@string/Suggest"
android:icon="@drawable/ic_lightbulb_outline_white_48dp"
android:orderInCategory="50"
app:showAsAction="ifRoom|collapseActionView" />
<item android:id="@+id/AbUndo"
android:title="@string/ActionBarUndo"
android:tooltipText="@string/ActionBarUndo"
android:icon="@android:drawable/ic_menu_revert"
android:orderInCategory="51"
app:showAsAction="ifRoom|collapseActionView" />
<item android:id="@+id/AbStep"
android:title="@string/ActionBarStep"
android:icon="@drawable/ic_play_arrow_white_24dp"
android:orderInCategory="100"
app:showAsAction="ifRoom|collapseActionView" />
.....
</menu>
Here is the code I used to get the View
associated to the AbErase menu item:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; mContext adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
actionBar.collapseActionView();
eraseItem = menu.findItem(id.AbErase);
View eraseItemView = eraseItem.getActionView();
int eraseItemViewLeft = eraseItemView.getLeft();
return super.onCreateOptionsMenu(menu);
}
When this code executes, eraseItemView is null. How can I get the Left coordinate of each individual icon in the menu?
Eventually, using the debugger, I found that the ToolBar
shown above has 3 children:
ActionMenuView
Linearlayout
that contains the Spinner
AppCompatImageButton
for the navigation buttonThe ActionMenuView
has 5 children of type ActionMenuItemView
. These are the icons I was looking for.
So to point to the bottom-left corner of the second icon, I use this code:
ViewGroup overflowMenu = (ViewGroup) scToolbar.getChildAt(0);
int bulbLeft = overflowMenu.getLeft() + overflowMenu.getChildAt(1).getLeft();