Programmatically set height on LayoutParams as density-independent pixels

前端 未结 5 2071
迷失自我
迷失自我 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:51

    Here is my snippet:

    public class DpiUtils {
    
        public static int toPixels(int dp, DisplayMetrics metrics) {
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
        }
    
    }
    

    where DisplayMetrics metrics = getResources().getDisplayMetrics()

提交回复
热议问题