Android: Convert pixel (dip) to density dependent pixel (ddp) size

For Android, one of the biggest problems is the wide variety of screen resolutions. What's worse is that the resolution is only one of three possible problems with positioning.

There is also screen size (the physical screen size such as 4.3") and pixel density (the number of pixels in a physical measurement such as CM or inches).

Starting from Android 1.6, this was simplified a great deal. The official documentation for supporting multiple screens can explain this MUCH better than I ever can here, so have a read of it.

Using this snippet, you can convert a hard-coded pixel value to something that is more relevant on the screen.

/**
* Converts the density independant pixel size to a density dependant pixel size.
*
* @param dip The intended pixel size.
* @return int The converted density dependant pixel size.
*/
public static int convertDensityPixel(int dip) {
return (int) (dip * yourActivity.getResources().getDisplayMetrics().density);
}

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog