Wednesday, May 16, 2012

19. Supporting different screen sizes

19.1. Using device independent pixel

Android devices are different in terms of resolution and in terms of density. Therefore it is recommended never to use fixed sized dimensions.
The unit of measurement which should be used is "dp" (which is the same as "dip" but shorter). dp refers to the base line of an Android device, e.g. 320x480 with 160dpi (dots per inch), which was the size of the first Android device (G1). This size is also known as mdpi (medium dots per inch).
If you specify the size in "dp", Android will automatically scale it, depending on the device. On a mdpi device "dp" will be equal to pixel but it will be smaller on a ldpi (approx. 120dip) and larger on a hdip (approx. 240dpi) device, so that it always occupies the same physical space.
You can use "dp" in your resources, e.g. layout files. The Android SDK expects that you specify everything in pixels. You can therefore use the following formulator to calculate the right amount of pixels for a dimension specified in dp.
    
public int convertToDp(int input) {
 // Get the screen's density scale
 final float scale = getResources().getDisplayMetrics().density;
 // Convert the dps to pixels, based on density scale
 return (int) (input * scale + 0.5f);
}
   

19.2. Using resource qualifiers

Android also allows to use resource qualifiers to specify that certain resources should only be used for certain resolutions or configurations. For example your can provide a special "main.xml" layout file for a device in landscape mode, if you place such a file in the "res/layout-land" folder.
The different resource qualifiers are described on the following webpage: Providing Resources

No comments:

Post a Comment