In the XML layout file, we can set both PX and dp (or DIP ). We usually choose to use DP to ensure the layout of machines with different screen resolutions is consistent. HoweverCodeHow to deal with it? Many control methods only provide the method for setting PX, such as setpadding, and do not provide the method for setting DP. At this time, if you need to set the DP, You need to convert the DP to PX.
The following is an application class that facilitates conversion between PX and DP.
Copy codeThe Code is as follows: Import Android. content. context;
Public class densityutil {
/**
* Convert the cell phone resolution from Dp to PX (pixel)
*/
Public static int dip2px (context, float dpvalue ){
Final float scale = context. getresources (). getdisplaymetrics (). density;
Return (INT) (dpvalue * scale + 0.5f );
}
/**
* Convert pixel to DP based on the resolution of the mobile phone
*/
Public static int px2dip (context, float pxvalue ){
Final float scale = context. getresources (). getdisplaymetrics (). density;
Return (INT) (pxvalue/scale + 0.5f );
}
}