1

I searched this question, and almost all of the answers are like this:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;

But the official document says widthPixels is The absolute width of the display in pixels. I run the code above on my Nexus 5, and the width equals 1080. Obviously it is an Pixel value. Is there anything I missed? How can I get a dip value of the screen?

tshepang
  • 12,111
  • 21
  • 91
  • 136
AngryYogurt
  • 755
  • 2
  • 7
  • 22
  • I don't think you can, DIP is density independent and not measured in actual realworld units. – PaulG May 23 '14 at 15:17
  • 1
    I'm not quite sure if it's correct, therfore only a comment.. dip == dp as said [here](http://stackoverflow.com/questions/2025282/difference-between-px-dp-dip-and-sp-in-android). Further, you can get px from dp and the other way round as given [here](http://stackoverflow.com/a/12147550/1798304). Therefore, I assume you can just combine what you've got with the answer of the 2nd link. – MalaKa May 23 '14 at 15:21
  • @MalaKa I did as you said, it works for me to use `float width_dp = dm.widthPixels / dm.density;` Thanks! – AngryYogurt May 23 '14 at 15:27

1 Answers1

2

you should convert the result to dips, like:

private int pixelsToDips(int pixels)
{
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pixels / scale + 0.5f);
}
fpanizza
  • 1,589
  • 1
  • 8
  • 15
  • What's the meaning of `0.5f`? I put a Button with `pixels / scale` width size, it really has a thin vacancy on the edge.When I use `pixels / scale + 0.5f` as you said, it exactly fit my screen.But why need to add `0.5f`?Does it applies all screen sizes? – AngryYogurt May 24 '14 at 00:03
  • I test `match_parent`, the thin vacancy disappear again in Android Studio.So I guess it is not necessary to add `0.5f` – AngryYogurt May 24 '14 at 00:13
  • 1
    If you cast `4.6f` to an int, the int will have 4 as a value. But if you add `0.5f` before casting the int will have the value 5. This means `int x = (int) (4.6f + 0.5f);` is the same as `int x = Math.round(4.6f)`. – MalaKa May 24 '14 at 13:31