1. 程式人生 > >測量 View 寬高,測到的數值是 px值,然後轉為 dp

測量 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之間的轉換