Programmatically set height on LayoutParams as density-independent pixels

前端 未结 5 2076
迷失自我
迷失自我 2020-12-07 08:24

Is there any way to set the height/width of a LayoutParams as density-independent pixels (dp)? It looks like the height/width, when set programmatically, are in pixels and n

5条回答
  •  渐次进展
    2020-12-07 08:31

    The answered solution didn't work for me, the height of the view was still off. I ended up with this, which works well:

    protected int dp2px(int dp){
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
    

    And if you want the other way round, pixels to dp ...

    protected float px2dp(float px){
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return Math.round(dp);
    }
    

提交回复
热议问题