Android UI Tutorial - Android Layout

Units Of Measurement

When specifying the size of an element on an Android UI, you should know the following units of measurement:

dp is Density-independent pixel.
1 dp is equivalent to one pixel on a 160 dpi screen.
This is the recommended unit of measurement when specifying the dimension of views. The 160 dpi screen is the baseline density assumed by Android. You can specify either "dp" or "dip" when referring to a density-independent pixel.

sp is Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes.

pt - Point.
A point is defined to be 1/72 of an inch, based on the physical screen size.

px - Pixel.
Corresponds to actual pixels on the screen. Using this unit is not recommended, as your UI may not render correctly on devices with a different screen resolution.

Convert Dp To Px

The formula for converting dp to px (pixels) is as follows:

pixels = dp * (dpi / 160)

where dpi is either 120, 160, 240, or 320.

If the Button on a 235 dpi screen, its actual width is

160 * (240/160) = 240 px.

When run on the 180 dpi emulator, which isregarded as a 160 dpi device, its actual pixel is now 160 * (160/160) = 160 px.

In this case, one dp is equivalent to one px.

You can use the getWidth() method of a View object to get its width in pixels:

public void onClick(View view) {
    Toast.makeText (this,String.valueOf(view.getWidth()),Toast.LENGTH_LONG).show();

Screen densities

Android defines and recognizes four screen densities:

  • Low density (ldpi) - 120 dpi
  • Medium density (mdpi) - 160 dpi
  • High density (hdpi) - 240 dpi
  • Extra High density (xhdpi) - 320 dpi

The screen of the Nexus S has a 4-inch screen diagonally, with a screen width of 2.04 inches.

Its resolution is 480 (width) 800 (height) pixels. With 480 pixels spread across a width of 2.04 inches, the result is a pixel density of about 235 dots per inch (dpi).

The Nexus S is regarded as a hdpi device, as its pixel density is closest to 240 dpi.

Using the dp unit ensures that your views are always displayed in the right proportion regardless of the screen density.