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 {
- /**
- * Switch from DP unit to PX (pixel) According to the resolution of the phone
- */
- Public static int dip2px (context context, float dpvalue) {
- Final Float scale = Context.getresources (). Getdisplaymetrics (). density;
- return (int) (Dpvalue * scale + 0. 5f);
- }
- /**
- * According to the resolution of the phone from PX (pixel) to the unit to become DP
- */
- Public static int Px2dip (context context, float pxvalue) {
- Final Float scale = Context.getresources (). Getdisplaymetrics (). density;
- return (int) (Pxvalue/scale + 0. 5f);
- }
- }
http://blog.csdn.net/arui319/article/details/6777133