Android - How does dp occupy different space in devices with different sizes?

1.3k views Asked by At

I searched a lot about dp, px, inch, pt etc.

From what I understood about 'dp':

Specifying 'dp' is simply a way to make Android draw the views with same size for devices with different screen densities. Eg, for a medium density device, each 'dp' will occupy a pixel. For a high density device - which has smaller pixels to fit more pixels per inch, 'dp' will occupy more than a pixel. For a low density device - which has larger pixels to fit less pixels per inch, 'dp' will occupy less than a pixel.

But what I also read is that space occupied by a 'dp' varies according to screen sizes, i.e for a small screen a 'dp' will occupy less space, while for a larger screen a 'dp' will occupy larger space. How exactly does this happen? From what I understood about 'dp', it should occupy the same amount of space in devices with differing screen sizes. Eg, a large screen of 240 dpi will have a 'dp' occupy 1.5 pixels, and so will be the case for a small screen of 240 dpi. Then how is it that a 'dp' will occupy different amount of space for different screen sizes?

What am I missing in my understanding of 'dp'? Please help.

2

There are 2 answers

4
Perraco On BEST ANSWER

Android defines a baseline dpi of 160 which is used as the reference to compute sizes for all screen densities:

pixel_size * (device_dpi / baseline_dpi) = result in "dp" units

>> or the other way around 

dp_size / (device_dpi / baseline_dpi) = result in "pixel" units

Therefore, 1 pixel in a 240dpi device is equivalent to 1.5dp units:

1 * (240 / 160) = 1.5

and the other way around, 1.5dp units in a 240dpi device is equivalent to 1 pixel

1.5 / (240 / 160) = 1

The important fact to know is that 160 is the baseline used as the reference for all DPIs. So, as dp units increase/decrease, the required pixels area to draw something translates into keeping the same size scale regardless of the device screen.

More information in the official documentation.

To be more clear:

The display size is not related to "dp units". The display size is just how big the display canvas is. The screen DPI defines how many dots fit in 1 square inch. And a "dp unit" is an abstract unit that, depending on the device's DPI, is scaled (up or down) to give "uniform dimensions" on any screen size, by using 160 as the baseline reference.

2
Rishabh Ritweek On

on the Android operating system a device-independent pixel is equivalent to one physical pixel on a 160 dpi screen. By this definition, you can understanddp has no relation with screen sizes as the scale is already fixed as 160 dpi.

.