Does setWidth(int pixels) use dip or px?

前端 未结 6 1388
执念已碎
执念已碎 2020-11-28 17:58

Does setWidth(int pixels) use device independent pixel or physical pixel as unit? For example, does setWidth(100) set the a view\'s width to 100 dips or 100 pxs?

Tha

6条回答
  •  遥遥无期
    2020-11-28 18:27

    Based on above answers which works fine to me, i generate some helper methods, just add them in your utils to use them in whole project.

       // value in DP
       public static int getValueInDP(Context context, int value){
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
        }
    
        public static float getValueInDP(Context context, float value){
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
        }
    
        // value in PX
        public static int getValueInPixel(Context context, int value){
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
        }
    
        public static float getValueInPixel(Context context, float value){
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
        }
    

提交回复
热议问题