来自getLocationOnScreen/getLocationInWindow的坐标不正确

nim*_*mph 57 android android-widget

呼叫getLocationOnScreen()getLocationInWindow()两者都给我一个top/Y大约约30px(状态/通知栏的高度)的坐标太远了.该left/X坐标上死了.

正如我上面所暗示的那样,我认为不同之处在于状态/通知栏...我可能是错的.我想如果我可以确定通知栏的大小,我可以解决这个问题但是,我很难做到这一点.

任何帮助将不胜感激.

nim*_*mph 81

我最终通过确定状态/通知栏的高度来解决这个问题,如下所示:

View globalView = ...; // the main view of my activity/application

DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
int topOffset = dm.heightPixels - globalView.getMeasuredHeight();

View tempView = ...; // the view you'd like to locate
int[] loc = new int[2]; 
tempView.getLocationOnScreen(loc);

final int y = loc[1] - topOffset;
Run Code Online (Sandbox Code Playgroud)

  • `int [] locInWindow = new int [2]; globalView.getLocationInWindow(locInWindow); topOffset = locInWindow [1];`//通过获取`globalView`的Y坐标来计算`topOffset` (8认同)

sat*_*ine 7

这是我喜欢获取状态栏高度,并调整偏移量的方法:

final int[] location = new int[2];
anchor.getLocationInWindow(location); // Includes offset from status bar, *dumb*
Rect anchorRect = new Rect(location[0], location[1],
        location[0] + anchor.getWidth(), location[1] + anchor.getHeight());

anchor.getRootView().findViewById(android.R.id.content).getLocationInWindow(location);
int windowTopOffset = location[1];
anchorRect.offset(0, -windowTopOffset);
Run Code Online (Sandbox Code Playgroud)

  • 可以假设窗口位于状态栏下方,因此偏移量不包括状态栏高度. (2认同)

use*_*844 5

我有同样的问题,尝试使用

offset = myView.GetOffsetY();
Run Code Online (Sandbox Code Playgroud)

并根据该值调整您的Y坐标,例如

coordY -= offset;
Run Code Online (Sandbox Code Playgroud)

提供``-method的类:

class MyView extends View {

  public int GetOffsetY() {
    int mOffset[] = new int[2];
    getLocationOnScreen( mOffset );
    return mOffset[1]; 
  }

}
Run Code Online (Sandbox Code Playgroud)