简体   繁体   English

在Android ActionBar中查找项目的位置

[英]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: 如果,我将action_bar_menu_layout设置为:

 <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. 因此通过使用crashActionView标志,一切正常。 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. 看起来只有在这种情况下,才使用该ID作为视图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: 然后我在侦听器中注册了GlobalLayoutListener:

    @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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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