Sobes.tech
Junior

Что такое px, dp и sp в контексте Android-разработки?

sobes.tech AI

Answer from AI

  • px (pixels): Pixels on the screen. These are actual dots that make up the display. The size in px depends on the screen density. On devices with different densities, the same size in px will occupy different physical areas.

  • dp (density-independent pixels): Density-independent pixels. A unit of measurement based on the physical size of the screen. dp ensures consistent physical size of UI elements across screens with different densities. 160 dp is approximately equal to 1 inch on a medium density (mdpi) screen. The Android framework scales dp according to the device's density.

  • sp (scale-independent pixels): Scale-independent pixels. Similar to dp, but additionally scaled based on the user's font size settings (e.g., font size in system settings). sp is recommended for setting text size.

Example usage in XML layout:

<TextView  
    android:layout_width="match_parent"  
    android:layout_height="wrap_content"  
    android:textSize="16sp"  // Text size in sp
    android:padding="8dp" /> // Padding in dp

<ImageView  
    android:layout_width="50dp"  // Image width in dp
    android:layout_height="50dp"  /> // Image height in dp

Summary table:

Unit Purpose Scales from Recommended for
px Physical pixel - Not recommended
dp Density-independent Screen density UI elements
sp Density-independent and scalable Screen density and font size Text