是不是经常有小伙伴在Activity的onCreate()方法中获取View的尺寸,结果通通为0,没错,此时就没有办法了吗?NO,下面这种方法就可以帮你简单的解决这些问题。
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(width, height);
int measuredWidth = view.getMeasuredWidth();
int measuredHeight = view.getMeasuredHeight();
ps:当然了你还可以通过添加ViewTreeObserver的2种方法也是可以的,记得要及时移除监听吆。方法没有最好,只有合适,根据情形选择合适的。
获取像素密度(非分辨率)
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float density = displayMetrics.density;//像素密度
获取系统认为的滑动距离阈值:
int scaledTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
获取手指滑动速度:
VelocityTracker velocityTracker = VelocityTracker.obtain();
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);//1000毫秒内滑动的距离,有正和负之分
float xVelocity = velocityTracker.getXVelocity();
float yVelocity = velocityTracker.getYVelocity();
return true;
在Application中获取屏幕尺寸(分辨率)
WindowManager windowManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(dm);
widthPixels = dm.widthPixels;