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
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;
}