实现效果:(button点击后,吐司弹出宽高)
主代码
final ViewTreeObserver vto =view.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
vto.removeOnPreDrawListener(this);
int height =view.getMeasuredHeight();
int width =view.getMeasuredWidth();
Toast.makeText(MainActivity.this, "height:" + height + " width: " + width, Toast.LENGTH_SHORT).show();
return true;
}
});
转换代码
//dp->px
public static int dipTopx(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
//px->dp
public static int pxTodip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}