What is the correct way to specify dimensions in DIP from Java code?

There is an existing utility method built called TypedValue.applyDimensions(int, float, DisplayMetrics) that does this.

Here’s how to use it:

// returns the number of pixels for 123.4dip
int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
                     (float) 123.4, getResources().getDisplayMetrics());

There’s a list of other types that you can use with it including COMPLEX_UNIT_SP, COMPLEX_UNIT_PT all found in the page I linked above. If you exclude the (int) typecast, you’ll get the floating point number.

I encountered the same problem and found this through poking around the code.

Leave a Comment