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 ();
display.getMetrics(outMetrics);
	
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.