In Android development, screen fitting is a very frustrating thing. Sometimes in this model debugging on the beautiful UI interface, changing a phone is ugly can't bear to look straight. But for our software to have a better user experience, we have to adapt to a variety of mobile phones on the Android market.
You are like the front-end people, in order to give users the best quality experience, they also need to adapt to a variety of different resolutions of the screen ah, but why they do not need to worry about this problem? Well, if that's because this thing-----percent. They can listen to the set percentage instead of forcing the width to be set to fit, so that their display does not differ significantly depending on the model. However, unfortunately, Android does not support this technology, only the DP SP units. So let's study these units.
Dip:device independent pixels (device independent pixels). Different devices have different display effects, this is related to the device hardware, generally we support WVGA, HVGA and QVGA recommend this, do not rely on pixels.
Dp:dip is the same.
Px:pixels (pixels). Different devices show the same effect, generally we hvga represent 320x480 pixels, this use more.
sp:scaled pixels (enlarge pixels). Mainly used for font display of best for textsize.
In the Android Typedvalue.java class, there is one of the following methods:
public static float applydimension (int unit, float value, displaymetrics metrics){
Switch (unit) {
Case COMPLEX_UNIT_PX:
return value;
Case COMPLEX_UNIT_DIP:
return value * metrics.density;
Case COMPLEX_UNIT_SP:
return value * metrics.scaleddensity;
Case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0F/72);
Case COMPLEX_UNIT_IN:
return value * METRICS.XDPI;
Case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}
Function: Convert units to pixels px.
Metrics.density: The default value is Density_device/(float) density_default;
Metrics.scaleddensity: The default value is Density_device/(float) density_default;
Density_device: For screen density
Density_default: Default value is 160
This concludes that the conversion formula for DP and PX is as follows:
PX = Dip * density/160
When density (screen density) =160, PX=DP
According to Google's suggestion, TextView's font size is best to use SP to do units, and view the source of TextView know that Android by default using the SP as the font size units. The dip is used as the unit for other elements.
About DP Dip DPI px