Determine DP for various screen size on Android Device

1.5k Views Asked by At

In android applications, we maintain dimen.xml for various screen resolutions. Say for example I am using device X as base development device and defining dimen.xml relative to device X. Now if I want to know what will be corresponding dimen.xml for a different density device what procedure/strategy can be followed here? For example: If I define margin_10 as 10dp in dimen.xml. what value margin_10 will have for different dimen.xml depending on density type (hdpi, xhdpi, xxhdpi, xxxhdpi)? Thanks

2

There are 2 best solutions below

0
On
    values folder containing dimens.xml file in which whatever screen size you 
    specified, it is consider as baseline as per google doc means 10dpx1 as per your question..
    now you set this size for different devices than procedure is like following.. create folder for different Screen Size
   1) values->dimens.xml [default as per base line hdpi] 10dp x 1.0
   2) values_sw320dp ->dimens.xml [xhdpi] 10dp x 1.5 result set to dimens.xml file of values_sw320dp folder
   3) values_sw480dp -> dimens.xml [for xxhdpi] 10dp x 2.0 result set to dimens.xml file of values_sw480dp folder
   4) values_sw640dp -> dimens.xml [for xxxhdpi] 10dp x 2.5 result set to dimens.xml file of values_sw640dp folder as like you can set size for all devices as per google document..
    here you just need to create folder and inside folder create dimens.xml file for working with different screen size in android.
0
On

Since you are defining the size in dp units, you need not worry about giving multiple sizes for other resolutions.

From the developer docs:

A dp is a density-independent pixel that corresponds to the physical size of a pixel at 160 dpi.

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.

It's the image resources or bitmaps which are provided for various densities

To generate images, you should start with your raw resource in vector format and generate the images for each density using the following size scale:

  • xhdpi: 2.0
  • hdpi: 1.5
  • mdpi: 1.0 (baseline)
  • ldpi: 0.75

Hope this helps.