我想在应用的 ActionBar
中的 MenuItem
下方显示一个小信息标签。
要正确定位它,我需要知道 MenuItem
的 x 位置。
到目前为止,Google 没有给我带来任何有用的结果。
有可能吗?
最佳答案
我找到了另一种方法来获取操作栏按钮的 Hook ,这可能比公认的解决方案更简单。
您可以简单地调用 findViewById
,并使用菜单项的 id!
现在最困难的部分是什么时候你可以这样称呼吗?在 onCreate
和 onResume
中,为时过早。一种方法是使用窗口的 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/