android - 如何获取 ActionBar MenuItem 的当前位置?

标签 android android-layout

我想在应用的 ActionBar 中的 MenuItem 下方显示一个小信息标签。 要正确定位它,我需要知道 MenuItem 的 x 位置。

到目前为止,Google 没有给我带来任何有用的结果。

有可能吗?

最佳答案

我找到了另一种方法来获取操作栏按钮的 Hook ,这可能比公认的解决方案更简单。 您可以简单地调用 findViewById,并使用菜单项的 id!

现在最困难的部分是什么时候你可以这样称呼吗?在 onCreateonResume 中,为时过早。一种方法是使用窗口的 ViewTreeObserver:

    final ViewTreeObserver viewTreeObserver = getWindow().getDecorView().getViewTreeObserver();
    viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            View menuButton = findViewById(R.id.menu_refresh);
            // This could be called when the button is not there yet, so we must test for null
            if (menuButton != null) {
                // Found it! Do what you need with the button
                int[] location = new int[2];
                menuButton.getLocationInWindow(location);
                Log.d(TAG, "x=" + location[0] + " y=" + location[1]);

                // Now you can get rid of this listener
                viewTreeObserver.removeGlobalOnLayoutListener(this);
            }
        }
    });

这在 onCreate 中。

注意:这是在使用 ActionBarSherlock 的项目上测试的,因此它可能不适用于“真实”操作栏。

关于android - 如何获取 ActionBar MenuItem 的当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10397613/

相关文章:

android - 使用 mp4parser ,如何处理从 Uri 和 ContentResolver 获取的视频?

android - 无法识别启动 Activity

android - 如何在点击它时获得 EditText 的值(value)?

android - 如何从android中的ArrayAdapter类调用下一页

android - 哪种嵌套布局顺序在 Android 中最有效

android - 如何将 android 库 (apklibs) 与 maven 和 eclipse 一起使用?

Android 在带有 EditText 的对话框中隐藏软键盘

安卓felix开发

android - 如何删除 Android Studio 中的库/模块?

android - 在 LinearLayout 中重叠 TextView