如何获取视图在坐标中的位置?

how to get view's position in coordinates?

您好,我在 RelativeLayout 中有一个 ImageView,现在我怎样才能获得图像视图在屏幕上的 X 和 Y 位置?

我试过了

getLocationOnScreen
log(mPhoto.getLeft());
log(mPhoto.getScrollX());
log(mPhoto.getX());
log(mPhoto.getTranslationX());

但全部 returns 0.

在以编程方式将 imageview 设置为居中后调用以上函数

    RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(mFaceWidth, mFaceHeight);
    lp1.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lp1.addRule(RelativeLayout.CENTER_VERTICAL);
    mPhoto.setLayoutParams(lp1);
    mPhoto.requestLayout();

试试这个:

int [] location = new int[2];
view.getLocationOnScreen(location);
x = location[0];
y = location[1];

试试这个

view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("trace", "Y: " + v.getY());
        }
    });

单击图像视图将在 logcat 中打印视图的视觉 Y 位置。

尚未测量所以我使用了以下 How can you tell when a layout has been drawn?

final LinearLayout layout = (LinearLayout)findViewById(R.id.YOUR_VIEW_ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 
        int x = layout.getX();
        int y = layout.getY();

    } 
});

View Tree Observer 回调将在视图呈现在屏幕上后调用。由于 view/layout 尚未呈现,上述方法将始终产生 0。

ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@Override public void onGlobalLayout(){
  int [] location = new int[2];
  view.getLocationOnScreen(location);
  x = location[0];
  y = location[1];
  view.getViewTreeObserver().removeGlobalOnLayoutListener(this);

}
}