Android 获取View在屏幕中的位置
获取View的位置
1 getLocationOnScreen: 计算该视图在全局坐标系中的x,y值,获取在当前屏幕内的绝对坐标(该值从屏幕顶端算起,包括了通知栏高度)。
2 getLocationInWindow ,计算该视图在它所在的widnow的坐标x,y值。
3 getLeft , getTop, getBottom, getRight, 这一组是获取相对在它父亲布局里的坐标。
注意:如果在Activity的OnCreate()事件输出那些参数,是全为0,要等UI控件都加载完了才能获取到这些数据。
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int[] location = new int[2];
v.getLocationOnScreen(location);
x = location[0];
y = location[1];
Log.d("123", "getLocationOnScreen x = " + x + " ; " + " y = " + y);
v.getLocationInWindow(location);
x = location[0];
y = location[1];
Log.d("123", "getLocationInWindow x = " + x + " ; " + " y = " + y);
Log.d("123", "left:" + v.getLeft());
Log.d("123", "right:" + v.getRight());
Log.d("123", "Top:" + v.getTop());
Log.d("123", "Bottom:" + v.getBottom());
Log.d("123", "Width:"+v.getWidth());
Log.d("123", "Height:"+v.getHeight());
}
});

浙公网安备 33010602011771号