tags:

views:

726

answers:

2

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?

Thanks.

A: 

pixels ofcource... the method is asking for pixels as parameter

josnidhin
If it is in layout xml file, we can specify android:layout_width="100dip" or android:layout_width="100px". In the source code, we can't specify the width of a layout as 100dip?
Not directly, you have to convert yourself using DisplayMetrics.density.
Romain Guy
+4  A: 

It uses pixels, but I'm sure you're wondering how to use dips instead. The answer is in TypedValue.applyDimension(). Here's an example of how to convert dips to px in code:

// Converts 14 dip into its equivalent px
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());
Daniel Lew
You can also call nbDips * getResources().getDisplayMetrics().density
Romain Guy
In fact, that's exactly what TypedValue.applyDimension() does. I considered posting that, but I like going through the API in case anything ever changes... though I guess it's safe to use that method if you give it the okay. :)
Daniel Lew
The applyDimension() version executes more code and it a bit more difficult to read I find. FWIW, the line I posted is what we actually use all over the place in the framework and standard apps.
Romain Guy