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

Pavel Lahoda picture Pavel Lahoda · Feb 10, 2010 · Viewed 40.6k times · Source

I found that it is possible to set dimensions of my interface elements in XML layouts using DIPs as in following fragment:

android:layout_width="10dip"

But all Java interface takes integer as arguments and there is no way to specify dimensions in DIPs. What is the correct way to calculate this?

I figured that I have to use property density of DisplayMetrics class but is this a correct way?

May I rely on this formula being always correct?

pixels * DisplayMetrics.density = dip

Is there a utility function for the conversion somewhere in Android?

Answer

sirhc picture sirhc · Apr 21, 2010

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.