0

I am really struggling with trying to handle the pixel density of screens. How do I make my application look the same on all devices? I thought the answer might be changing the units from dp to px:

public static int dpToPx(int dp) {
    return (int)(dp / Resources.getSystem().getDisplayMetrics().density);
}

But this didn't seem to work either and I can't seem to find an answer on how to handle this.

Ryan
  • 727
  • 2
  • 14
  • 31

1 Answers1

1

If you are in an activity or fragment then, you can call the getResources() method. Then you can convert the dp to px by the below method:

Formula: px = dp * density

public static int dpToPx(int dp) {
    return (int)(dp * getResources().getDisplayMetrics().density);
}
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • Tried this and it didn't work. I then realized it was **px** to **dp** that I wanted instead. And what I found was peculiar. When I would print the display dimensions with the method `pxToDp(act.getResources().getDisplayMetrics().widthPixels)` I would consistently get 731 regardless what the resolution was set to. But when I would call the `pxToDp` method on the coordinated and dimensions of a `Path` object that draws a `RoundRect` the dimensions and coordinates would not be in the same relative location. Why is this? – Ryan Aug 04 '17 at 03:26