Friday, April 27, 2012

How to get Width and Height in Android Density Pixel (DP)

Android recommends to use Density-independent Pixel (dp) instead of Pixels in order to scale views based on the current screen density. In order to get the width and height of the android in "dp" units, you can use the following code.

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

This code is independent of the container view and could be used to calculate screen size and draw custom user interface.


  1. Nice post!

    What I do first is to design with photoshop the elements of my app and then i resize the images with an app called Design for multiple densities

    Worth to take a look!