7

Is it possible to specify the pixel unit in code. What I mean is, say I have a layout and I want the size to be 20dp, then is there any way to do so without writing in a layout xml

pankajagarwal
  • 13,462
  • 14
  • 54
  • 65

2 Answers2

29

In a view:

DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);

In an Activity, of course, you leave off the getContext().

To convert from scaled pixels (sp) to pixels, just use metrics.scaledDensity instead of metrics.density.

EDIT: As @Santosh's answer points out, you can do the same thing using the utility class TypedValue:

DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
int pixels = Math.round(fpixels);

For sp, substitute TypedValue.COMPLEX_UNIT_SP for TypedValue.COMPLEX_UNIT_DIP.

Internally, applyDimension() does exactly the same calculation as my code above. Which version to use is a matter of your coding style.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 3
    To round up, this is what the framework does. This ensures that the size will never be 0px. – Romain Guy Feb 16 '11 at 06:29
  • @sebrock - Because OP wanted the size to be 20dp and making it a float to start with eliminates an int-to-float conversion when calculating `pixels` two lines later. – Ted Hopp Oct 26 '11 at 21:17
  • sry to bring up an old topic but i have a question. What if i have a value stored in a variable that i want the dp equal to. For example if i have a random value stored in the variable num how do i replace the 20f with numf. – MikeC Aug 11 '12 at 21:19
  • @MikeT - I don't quite understand the problem. If you want to use the sample code I posted, just use the variable instead of `dp` (or assign `dp` the value of your variable: `float dp = randomVariable;`). – Ted Hopp Aug 12 '12 at 02:59
  • 1
    @wviana - You would use `metrics.scaledDensity` instead of `metrics.density` in the last line. I'll update the answer to include that information. Thanks for asking. – Ted Hopp Apr 12 '16 at 16:53
  • @Fattie - That's a good solution for setting text size. But it doesn't generalize to other cases (say, setting a layout dimension in code). Also, that API call has been around since Android 1, so it isn't new for 2021. – Ted Hopp Mar 03 '21 at 15:30
4

You can use

float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());

now, the value of pixels is equivalent to 20dp

The TypedValue contains other similar methods that help in conversion

Santosh
  • 13,251
  • 5
  • 24
  • 12