difference between "px", "dip", "dp" and "sp" in Android


px
Pixels - corresponds to actual pixels on the screen

dp or dip  Density-independent pixel (dp)
Density-independent Pixels - an abstract unit type that is based on the physical density of the mobile phone screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel changes with change in the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dp" and "dip", though "dp" is more consistent with "sp".

spScale-independent Pixels
- this is like the dp unit, but it is also scaled by the user's font size preference. It is recommended you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.
Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities.
So, when should you use sp and when you should you use dp?
Use sp for text size…because but it is scaled by the user’s font size preference.
Use dp for everything else.
Example:
<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Hello, world!”
android:textSize=”30sp”
android:padding=”15dp”/>
<Button
android:layout_width=”40dp”
android:layout_height=”wrap_content”
android:layout_marginLeft=“20dp”/>



No comments:

Post a Comment

Popular Posts