简体   繁体   中英

Find position of item in Android ActionBar

Is there a way to find the position of an icon in the action bar?

I have used the code below:

final View actionBarView = getActivity().getWindow().getDecorView().findViewById(getResources().getIdentifier("action_bar_container", "id", "android"));

if (actionBarView != null) {
    final View buttonInActionBar = actionBarView.findViewById(R.id.menu_item);
    if (buttonInActionBar != null) {

If, I set action_bar_menu_layout like this:

 <item
        android:id="@+id/menu_item"
        MyApp:actionProviderClass="my_provider"
        MyApp:showAsAction="always|withText|collapseActionView"
        android:orderInCategory="0"
        android:title="@string/item_name"/>

so by using the collapseActionView flag, everything works. But without that flag the view is not found. It looks like only in that case the menu is build by using that id as the view id.

Is there a way to do it?

This is the way I did it.

I used:

mItemView = MenuItemCompat.getActionView(menu.findItem(R.id.menu_item));

then I registered a GlobalLayoutListener and in the listener:

    @SuppressWarnings("deprecation")
    @Override
    public void onGlobalLayout() {
        mItemView.getLocationInWindow(mMyItemLocation);
        if (mItemView == null || mMyItemLocation[0] == 0  || mItemView.getRight() == 0 || mItemView.getWidth() == 0) {
            return;
        }
        mLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM