Programmatically set height on LayoutParams as density-independent pixels

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

    Since it may be used multiple times:

    public static int convDpToPx(Context context, float dp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    }
    

    I found it more practical to use the conversion rate, as usally more than one value has to be converted. Since the conversion rate does not change, it saves a bit of processing time.

    /**
     * Get conversion rate from dp into px.
    * E.g. to convert 100dp: px = (int) (100 * convRate); * @param context e.g. activity * @return conversion rate */ public static float convRateDpToPx(Context context) { return context.getResources().getDisplayMetrics().densityDpi / 160f; }

提交回复
热议问题