7

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.

700 Software
  • 85,281
  • 83
  • 234
  • 341
  • Please see my post regarding converting Points to Pixels http://systemdotrun.blogspot.co.uk/2014/09/whats-point-in-font-sizing.html? – Dori Oct 06 '14 at 18:17
  • 1
    The blog linked in the above comment has moved to https://doridori.github.io/Whats-the-Point-(in-fonts-sizing) – digawp Sep 26 '18 at 06:22

2 Answers2

11

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);
Yahel
  • 8,522
  • 2
  • 24
  • 32
1

You can use dip instead of pt

Aman Alam
  • 11,231
  • 7
  • 46
  • 81
  • 1
    I am using pt instead of dip because it makes more sense to the non programmers. If somebody asks how big that is I can say 12 points and they can know what that is. If I say pixels then they may not realize the Android pixels are much smaller then they are on PC and if I say dips then they will be faced with a new word. All that aside. Can I use dip at runtime? Can I convert pt to dip? – 700 Software Jan 20 '11 at 16:47
  • With regards to your dip at runtime question. Yes you can, but you have to convert Pixels to DPs by multiplying the pixels with the screens scale factor which you can get with context().getResources().getDisplayMetrics().density. – C0deAttack Jan 20 '11 at 17:05