Search code examples
androidandroid-layoutdpi

Android: Understanding the DPI and getting it via code?


Can anyone help, i am finding it difficult to get the DPI of a handset, mentally (understanding it) and get the value in code :-)

For example, it states the density is the following (taken from android docs)

ldpi    Resources for low-density (ldpi) screens (~120dpi).
mdpi    Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpi    Resources for high-density (hdpi) screens (~240dpi).
xhdpi   Resources for extra high-density (xhdpi) screens (~320dpi).

but why is it only state as ~240dpi, ie. one value? should it not be (for example) a mobile (samsung galaxy S2) is of WVGA (800 x 480) (DPI), what does the symbol ~ mean?

So taking a simple example of 800 x 480 (the dpi of a samsung galaxy s2), how is this converted into one of the values above?

I wonder if anyone can help me mentally understand this.

Then later is it possible via code to get the Density Size, DPI (including x and y) via code?

I am a little lost


Solution

  • but why is it only state as ~240dpi, ie. one value?

    What were you expecting?

    what does the symbol ~ mean?

    As the commenters pointed out, this means "approximately". In reality, device manufacturers will choose what density bucket they want their device to be in, typically based on their testing with the behavior of real-world apps. Generally, they will choose the closest density bucket to their actual screen density, but this is not guaranteed.

    So taking a simple example of 800 x 480 (the dpi of a samsung galaxy s2), how is this converted into one of the values above?

    You don't. Resolution is not density. I could have an 800x480 display that is 1mm, 1cm, 1m, or 1km in diagonal size. Each of those would have a different screen density as a result. Density is measured in dpi = "dots" per inch = pixels per inch.

    Then later is it possible via code to get the Density Size, DPI (including x and y) via code?

    Yes, from a DisplayMetrics object.