Screen Pixel Densities

In activity_main.xml, you specified attribute values in terms of dp units. Now it is time to learn what they are.

Sometimes you need to specify values for view attributes in terms of specific sizes (usually in pixels, but sometimes points, millimeters, or inches). You see this most commonly with attributes for text size, margins, and padding. Text size is the pixel height of the text on the device’s screen. Margins specify the distances between views, and padding specifies the distance between a view’s outside edges and its content.

As you saw in the section called Adding an Icon, Android automatically scales images to different screen pixel densities using density-qualified drawable folders (such as drawable-xhdpi). But what happens when your images scale, but your margins do not? Or when the user configures a larger-than-default text size?

To solve these problems, Android provides density-independent dimension units that you can use to get the same size on different screen densities. Android translates these units into pixels at runtime, so there is no tricky math for you to do (Figure 2.9).

Figure 2.9  Dimension units in action on TextView

Dimension units in action on TextView

px

Short for pixel. One pixel corresponds to one onscreen pixel, no matter what the display density is. Because pixels do not scale appropriately with device display density, their use is not recommended.

dp

Short for density-independent pixel and usually pronounced dip. You typically use this for margins, padding, or anything else for which you would otherwise specify size with a pixel value. One dp is always 1/160 of an inch on a device’s screen. You get the same size regardless of screen density: When your display is a higher density, density-independent pixels will expand to fill a larger number of screen pixels.

sp

Short for scale-independent pixel. Scale-independent pixels are density-independent pixels that also take into account the user’s font size preference. You will almost always use sp to set display text size.

pt, mm, in

These are scaled units, like dp, that allow you to specify interface sizes in points (1/72 of an inch), millimeters, or inches. However, we do not recommend using them: Not all devices are correctly configured for these units to scale correctly.

In practice and in this book, you will use dp and sp almost exclusively. Android will translate these values into pixels at runtime.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.24.134