Programmatically set height on LayoutParams as density-independent pixels

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

     public static int getDPI(int size, DisplayMetrics metrics){
         return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;        
     }
    

    Call the function like this,

    DisplayMetrics metrics;
    metrics = new DisplayMetrics();         
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    int heigh = getDPI(height or width, metrics);
    

提交回复
热议问题