In the XML layout file, we can either set the PX or set the DP (or DIP). In general, we will choose to use DP, which will ensure that the layout of different screen resolutions on the machine is consistent. But in the code, how to deal with it? Many of the methods in the control provide only a method for setting PX, such as setpadding, and do not provide a way to set the DP. At this point, if you need to set the DP, it is necessary to convert the DP into PX. The following is an application class that facilitates the conversion between PX and DP. Import Android.content.Context; public class Densityutil {/** * turns from DP units to px (pixels) */public static int dip2px (context context, float Dpvalue) based on the resolution of the phone {
Final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Dpvalue * scale + 0.5f);
}/** * from PX (pixel) units to DP * Depending on the resolution of the phone
public static int Px2dip (context context, float Pxvalue) {
Final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue/scale + 0.5f);
}
Convert between DP and PX in Android