Difference of px, dp, dip and sp in Android
px is one pixel.
Pixels – corresponds to actual pixels on the screen.
Points – 1/72 of an inch based on the physical size of the screen.
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.
** UPDATE: Android Complete tutorial now available here.
The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.
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.
Scale-independent Pixels – this is like the dp unit, 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 user’s preference.
Use of dp:
Your application achieves “density independence” when it preserves the physical size (from the user’s point of view) of user interface elements when displayed on screens with different densities. (ie) The image should look the same size (not enlarged or shrinked) in different types of screens.
The Android system helps your application achieve density independence in two ways:
- The system scales dp units as appropriate for the current screen density
- The system scales drawable resources to the appropriate size, based on the current screen density, if necessary.
However to optimize your application’s UI for the different screen sizes and densities, you can provide alternative resources for any of the generalized sizes and densities. Typically in usual practice it is advisable that you provide alternative layouts for some of the standard screen sizes and alternative bitmap images for different screen densities. At runtime, the system uses the appropriate resources for your application, based on the generalized size or density of the current device screen.