Android: Convert points to pixels

700 Software picture 700 Software · Jan 20, 2011 · Viewed 10.1k times · Source

I have been using the pt unit in XML files. Now I need to set the width of an element at runtime. How can I set the width by points so that it is the same unit I have been using everywhere else. I assume I will need to multiply by resolution and dpi. A code sample would be best.

Answer

Yahel picture Yahel · Jan 20, 2011

First you should really read the following in-depth article from the Android Developer Documentation :

http://developer.android.com/guide/practices/screens_support.html

Right in the middle you'll find the following under the title :

Do not use hard-coded pixel values in your code

// Convert the dps to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);