What are differences between px, dp and sp in Android ?
Today, a brief reminder about Android dimensions. When you create the UI layouts of your application, you’re used to define dimensions with units like dp (density-independent pixels), dip or sp (scale-independent pixels). Other units supported are pt (points), px (pixels), mm (millimeters) and in (inches) where as this second kind of units is not recommended because not independent from devices screen pixels.
So, to be clear, Android standard recommend to use the following units :
- sp for font-sizes because, like dp, it’s independent pixels but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user’s preference.
- dp for everything else. Observe that dp == dip. Indeed, dip was used in old Android versions and is deprecated. Now, we must use dp.
Advantages of dp are simple to understand but this is what Android documentation tells about dp :
Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.
Android uses a set of six generalized densities for devices :
- ldpi (low) ~120dpi
- mdpi (medium) ~160dpi
- hdpi (high) ~240dpi
- xhdpi (extra-high) ~320dpi
- xxhdpi (extra-extra-high) ~480dpi
- xxxhdpi (extra-extra-extra-high) ~640dpi
Other units must be avoided when you want to make application that support multiple devices screen.
However, here are some informations about these units :
- px
Pixels – corresponds to actual pixels on the screen. - in
Inches – based on the physical size of the screen.
1 Inch = 2.54 centimeters - mm
Millimeters – based on the physical size of the screen. - pt (it depends upon physical size of the screen) Points – 1/72 of an inch based on the physical size of the screen.
The table below summarizes all the informations about Android dimensions :
Leave a Reply
You must be logged in to post a comment.