嗨我在RelativeLayout里面有一个ImageView,现在我怎样才能在屏幕上获得imageview的X和Y位置?
我试过了
getLocationOnScreen
log(mPhoto.getLeft());
log(mPhoto.getScrollX());
log(mPhoto.getX());
log(mPhoto.getTranslationX());
但所有人都返回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();
答案 0 :(得分:5)
在屏幕上呈现视图后,将调用View Tree Observer回调。上面的方法总是会产生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);
}
}
答案 1 :(得分:3)
试试这个
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("trace", "Y: " + v.getY());
}
});
单击图像视图将在logcat中打印视觉Y视图位置。
答案 2 :(得分:2)
试试这个:
int [] location = new int[2];
view.getLocationOnScreen(location);
x = location[0];
y = location[1];
答案 3 :(得分:0)
尚未测量,因此我使用了以下内容 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();
}
});