When I recently made an XML file layout, to use to get the height of the screen, I use the real machine is millet 2S, screen resolution is 1280*720, of course, its unit is not a DP in the layout file, and then I went online to check the resolution of the Unit and the relationship between the DP and the conversion mode, here made a summary:
First, take a look at their basic concepts:
PX: Is the pixel point of the screen
DP: An abstract unit based on density, if a 160dpi screen, 1dp=1px
dip: equivalent to DP
SP: Similar to DP, unit of text
For the dip and PX relationship, do the following overview:
A pixel is usually considered as the smallest complete sample of the image, which is used more often, especially in web development, where the page is mostly used as a unit of pixels.
2). Dip or DP (device independent pixels):
Device independent pixel-this is related to the device hardware, we generally support the mobile phone on a variety of resolutions, such as WVGA, HVGA
And QVGA, will use dip as a unit of length
Here's a look at the phone screen type and density and resolution of the corresponding relationship
QVGA screen density=120 QVGA (240*320)
HVGA screen density=160 HVGA (320*480)
WVGA screen density=240 WVGA (480*800)
WQVGA screen density=120 WQVGA (240*400)
Note: The density value represents the number of display points per inch, and the resolution is two concepts.
DP and PX Conversion formula:
pixs =dips * (densitydpi/160).
dips= (pixs*160)/densitydpi
But we also need to have an offset value when we convert inside the code: 0.5f
Conversion between
Pixels and DP
| code is as follows |
copy code |
Public int dp2px (context, float DP) {
Final float s Cale = Context.getresources (). Getdisplaymetrics (). density;
Return (int) (DP * scale + 0.5f);
}
Public int PX2DP (context, float px) {
Final float scale = Contex T.getresources (). Getdisplaymetrics (). density;
Return (int) (Px/scale + 0.5f);
}
|
Here, I'll post the code to get the height of the screen:
| The code is as follows |
Copy Code |
|
Displaymetrics dm = new Displaymetrics ();
Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);
int width = dm.widthpixels;
int height = dm.heightpixels;
|
We see here that the scale is the global variable defined in this class displaymetrics, in fact this value is the current mobile phone density/160,scaledensity is used to convert between PX and SP and scale almost. And one thing is that there's an offset value to be processed here.
DP This unit may be unfamiliar to web developers because they are typically px (pixels).
But now, after starting Android apps and games, basically switching to DP units because they can support multiple-resolution handsets.