What is the difference between `px`, `dp`, `dip`, and `sp` units in Android?
Instruction: Explain each unit and when it's appropriate to use them in designing Android applications.
Updated
Official answer
px is a rendered pixel unit. A fixed number of pixels can occupy different apparent sizes at different display densities, so it is usually inappropriate for fixed layout dimensions.
dp and dip name the same density-independent unit. Android converts dp using the configured logical display density: approximately px = dp × densityDpi / 160, with rounding as needed. Thus 24 dp is 24 px at 160 dpi and 48 px at 320 dpi. This is a layout-density convention, not a guarantee of identical physical millimeters on every device.
sp is intended for text sizing and accounts for the user's font preference as well as density. Starting with Android 14, large font scaling can be nonlinear: do not convert sp by blindly multiplying by one scaledDensity or fontScale factor. Prefer XML/Compose text sizing or the supported dimension-conversion APIs.
Use dp for ordinary spacing and control dimensions, sp for text, and pixels when an API explicitly deals with bitmap or drawing coordinates after conversion. These units alone do not make a layout adaptive. Let content wrap/reflow, avoid text containers with inadequate fixed heights, and test large font settings, window resizing and different densities.