androidscreenpixeldensity-independent-pixelscreen-density

Android - Puzzles about conversion between dp and pixel


I know this might be a silly question but I have really gone through so many materiel and links but still not quite understand it. In the "Supporting Multiple Screens" section of Android Develop Doc, it introduces dp like this:

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Basically I understand the fact that screen with higher dpi would have more pixels in a single physical inch, which means a dp in such a screen would equal more physical pixels(px).

But according to the above conversion equation (in bold font), in a screen with higher dpi (e.g. 240 dpi screen) , a px = (240 / 160) * dp = 1.5dp. This seems to mean that in higher dpi screen a px would equal more dp. This looks in conflict with my previous understanding.

So, please, could anyone help me to figure this tricky issue out. Thank you a lot, really.


Solution

  • You are looking at the wrong place in the formula. To see how many dp equals one px in different density, lets rearrange the formula:

    px = dp * (dpi/160)
    dp = px / (dpi/160)
    

    Now for 1px, in mdpi devices:

    dp = 1 / (160/160) = 1dp
    

    In hdpi devices:

    dp = 1 / (240/160) = 0.666666667dp
    

    You can see that 1px equals less dp in higher density devices