skip to content

Resources and Layouts

Resource qualifiers for density, width, night mode and locale, View layouts with ConstraintLayout, themes and view binding. Asked to check you can serve many screens without duplicate layouts.

on this pageshow

explore

questions

5

On Android, what do dp, sp and px measure, and which unit belongs on a view's margin versus its text size?

level: juniorimportance: must knowfreq 78%

answer

  1. physical versus virtual pixels
  2. baseline density of 160 dpi
  3. the user's font-size setting
  4. DisplayMetrics.density as the scale

basics

~20 s

px is a physical screen pixel; dp is a density-independent pixel equal to one pixel at 160 dpi; sp is a dp that also follows the user's font-size setting. Use dp for margins and sizes, sp for text.

solid answer

~40 s

A `px` is one physical pixel, so the same number of pixels looks larger on a low-density screen than on a dense one. A `dp` is a virtual pixel equal to one pixel at the 160 dpi baseline; Android converts it with `px = dp * (dpi / 160)`, which is the `DisplayMetrics.density` factor (1.0 at mdpi, 2.0 at xhdpi). An `sp` is the same size as a dp by default but grows or shrinks with the user's preferred text size. So margins, paddings and view sizes go in `dp`, `android:textSize` goes in `sp`, and you never use `sp` for layout sizes. When code needs pixels, convert with `TypedValue.applyDimension()` instead of hardcoding the formula.

code

xml · 19 lines
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <Button
        android:id="@+id/read_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="@string/read_more" />
</LinearLayout>

go deeper

for a junior

Recall the three definitions, the 160 dpi baseline, and the rule: dp for sizes and spacing, sp for text, px almost never in a layout.

for a middle

Explain the conversion through DisplayMetrics.density, why TypedValue.applyDimension beats a hand-written formula, and how density buckets and vector drawables handle bitmaps.

for a senior

Show you have shipped for large font scales: wrap_content text containers, testing at the largest font size and at several densities, and catching px values in review.

for a principal

Treat units as a team convention: lint or review rules that reject px and sp-for-spacing, and a vector-first asset policy that keeps the APK small.

## Why Android needs more than one unit Android phones and tablets ship with very different **pixel densities**: one screen may fit 160 pixels into an inch, another 480. If a layout is written in raw pixels, a button that is 100 pixels wide is a comfortable target on the first screen and a tiny one on the second. Android's answer is to describe sizes in units that are independent of density and let the framework translate them into real pixels for the screen at hand. | Unit | What it measures | Scales with density | Scales with the user's font size | Use it for | |---|---|---|---|---| | `px` | One physical pixel | No | No | Almost nothing in layouts; pixel maths inside drawing code | | `dp` (or `dip`) | A virtual pixel, one pixel at 160 dpi | Yes | No | Margins, paddings, view widths and heights, touch targets | | `sp` | A dp that also follows the text-size preference | Yes | Yes | `android:textSize` and other text sizes | ## How dp becomes pixels The **baseline density** is medium density (mdpi), about 160 dpi. At that density one dp is one pixel. Everywhere else Android applies: ``` px = dp * (dpi / 160) ``` The factor `dpi / 160` is exposed as `DisplayMetrics.density`: - **0.75** on a low-density (ldpi) screen - **1.0** on a medium-density (mdpi) screen - **1.5** on a high-density (hdpi) screen - **2.0** on an extra-high-density (xhdpi) screen So a view declared as `100dp` wide is 100 pixels on mdpi, 150 on hdpi and 200 on xhdpi, and it appears roughly the same physical size on all three. The Android documentation is explicit that you should not hardcode this equation in app code. When code needs a pixel value (a gesture threshold, a custom drawing offset), call `TypedValue.applyDimension()` with `COMPLEX_UNIT_DIP` and the current `resources.displayMetrics`; it converts dp, sp and other dimension types for you. For framework distances such as the scroll threshold, `ViewConfiguration` already offers pixel values through its `getScaled...` methods, for example `getScaledTouchSlop()`. ## Why text uses sp, and layouts never do An `sp` (scale-independent pixel) starts out the same size as a dp. The difference is that it also responds to the **text size the user chose in system settings**. A reader with low vision who raises the font size expects every app's text to grow; declaring `android:textSize="20sp"` gives them that. The documentation's rule is equally firm in the other direction: **never use sp for layout sizes**. If margins or container heights were in sp, raising the font size would also inflate spacing and break the layout's proportions. The usual pattern is: 1. Put spacing, sizes and icons in `dp`. 2. Put text sizes in `sp`. 3. Let containers that hold text size themselves with `wrap_content`, so larger text has room instead of being clipped. ## Density buckets for bitmaps Units solve sizes; bitmaps need a second tool. Android groups screens into density buckets (`ldpi`, `mdpi`, `hdpi`, `xhdpi`, `xxhdpi`, `xxxhdpi`) with a **3:4:6:8:12:16** scaling ratio, so an icon that is 24 by 24 pixels at mdpi should be 48 by 48 at xhdpi. You can supply one bitmap per bucket in qualified `drawable-` directories, but the documentation recommends **vector drawables** first, because one vector file renders sharply at every density. Launcher icons belong in `mipmap-` directories, which are all kept in the APK so a launcher can pick a higher-density icon than the device's own bucket. A density qualifier does not mean "only for this density". If an hdpi phone finds no `drawable-hdpi/` copy, Android takes the closest bucket it has and scales the bitmap, preferring to scale a larger image down rather than a smaller one up. That keeps the app working, but the scaled image costs memory and may look soft, which is why a missing bucket shows up as a quality problem rather than a crash. ## Common mistakes - Writing sizes in `px` because they "look right" on the developer's own phone. - Using `sp` for margins in the belief that it makes the whole layout accessible. - Fixing a text container's height in dp, so sp text clips when the font size rises. - Multiplying by a hardcoded constant instead of using `DisplayMetrics.density` or `TypedValue.applyDimension()`. - Shipping one large bitmap and letting Android scale it everywhere, which wastes memory on small screens and blurs on dense ones. A quick way to test all of this is to run the app on an emulator with a different density and with the largest system font size: dp-based spacing should look the same, and text should grow without being cut off.

  • Why is a fixed-height container around sp text a problem?
    Because `sp` text grows when the user raises the system font size while a `dp` height does not. The text overflows and is clipped. Give the container `wrap_content` (or a minimum height) so it grows with the text, and test with the largest font setting.
  • How do you turn 16dp into pixels inside a custom view?
    Call `TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16f, resources.displayMetrics)`, or multiply by `resources.displayMetrics.density`. Both use the current screen's scale factor; hardcoding `dpi / 160` or a constant like 3 breaks on other densities.

  • A dp is always exactly one physical pixel on every device.
  • Margins should be in sp so the whole layout scales for accessibility.
  • Pixel values are fine because modern phones all share one density.
  • sp ignores the user's font size unless the app opts in.
  • Converting dp to pixels by multiplying by a fixed constant such as 3.
open as a page

How does Android choose among res/ directories such as layout-sw600dp, values-night and values-ar when a news app starts on a device?

level: middleimportance: must knowfreq 66%

basics

~20 s

Android resolves each resource separately: it discards directories that contradict the device configuration, then walks the qualifier precedence table, keeping only directories with the highest-precedence qualifier any candidate uses, until one remains. Density picks the closest bucket.

open as a page

What does Android view binding generate from an XML layout, and what does it fix compared with findViewById?

level: juniorimportance: should knowfreq 58%

basics

~20 s

View binding generates one class per layout, such as ResultProfileBinding, with a typed field for every view that has an id plus a root reference. Wrong ids or types fail at compile time instead of crashing at runtime.

open as a page

In Android's View system, how does a style differ from a theme, and why do DayNight layouts reference colours through ?attr/ rather than @color/?

level: middleimportance: should knowfreq 52%

basics

~20 s

A style sets attributes on the one view it is applied to; a theme names resources for a whole app, activity or view subtree. ?attr/ references resolve against the current theme, so DayNight can swap them.

open as a page

An Android news article screen built from deeply nested LinearLayouts with layout_weight is slow to lay out; how do the View measure and layout passes explain it, and what would you change?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Views are measured, then laid out, top-down before drawing. A weighted LinearLayout may measure its children twice, and nesting compounds that work. Flattening the screen into one ConstraintLayout with 0dp constraints and weighted chains cuts that repeated work.

open as a page