- 默认的滚动都是基于layout的
- setTranslationX是在layout的基础上进行偏移
一、dip, dp, px, sp区别
我们在Android代码中获取到的宽高坐标等基本全都是px
- dip: device independent pixels(设备独立像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这 这个,不依赖像素。
- dip(value)=(int) (px(value)/1.5 + 0.5)
- dp: 很简单,和dip是一样的。
- px: pixels(像素),不同的设备不同的显示屏显示效果是相同的,这是绝对像素,是多少就永远是多少不会改变。
- sp: scaled pixels(放大像素). 主要用于字体显示best for textsize
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
二、控件坐标 与 点击事件坐标
2.1 控件坐标
2.1.1 相对父布局的相对坐标
- getTop:获取到的,是view自身的顶边到其父布局顶边的距离
- getLeft:获取到的,是view自身的左边到其父布局左边的距离
- getRight:获取到的,是view自身的右边到其父布局左边的距离
- getBottom:获取到的,是view自身的底边到其父布局顶边的距离
2.1.2 相对屏幕和窗口的绝对坐标
- getLocationOnScreen ,计算该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是说包括了通知栏的高度)//获取在当前屏幕内的绝对坐标
- getLocationInWindow ,计算该视图在它所在的widnow的坐标x,y值,//获取在整个窗口内的绝对坐标(譬如,在dialog中)
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
2.2 点击事件坐标
- getX():获取点击事件相对控件左边的x轴坐标,即点击事件距离控件左边的距离
- getY():获取点击事件相对控件顶边的y轴坐标,即点击事件距离控件顶边的距离
- getRawX():获取点击事件相对整个屏幕左边的x轴坐标,即点击事件距离整个屏幕左边的距离
- getRawY():获取点击事件相对整个屏幕顶边的y轴坐标,即点击事件距离整个屏幕顶边的距离