测量 View 宽高,测到的数值是 px值,然后转为 dp

实现效果:(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);
}

Android 获取控件的宽高 dp和px之间的转换

猜你喜欢

转载自blog.csdn.net/qq_38340601/article/details/82968447