Android sometimes need to get the size of the screen to control the position of the control, recently done some research, now the method to get the screen size information summarized below, there may be some local understanding is not comprehensive.
1.getMetrics
Java code
- Displaymetrics DM = new Displaymetrics ();
- Activity.getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);
- In the absence of an activity context, you can use the following methods, which require context contexts
- DM = Context.getresources (). Getdisplaymetrics ();
- int screenwidth = Dm.widthpixels; //Width
- int screenheight = Dm.heightpixels; //Height
This method gets the actual size of the screen (that is, the screen resolution). However, after the API one (Android 3.0), Google to reduce the problem of fragmentation to unify the standard, it is recommended to delete the phone's entity key. So now most mobile phones no longer have physical keys, optionsmenu are usually moved to the upper right corner. However, when the target API is set to 11 or below, the app will generate a virtual menu button at the bottom, and if you want to get the information to remove the actual display area of the key area, the above method will not work. Find the document, Android.view.Display there is another function getrealmetrics to get the actual display area
2.getRealMetrics (Note that this method is only available for API 17)
Java code
- Displaymetrics DM = new Displaymetrics ();
- Activity.getwindowmanager (). Getdefaultdisplay (). Getrealmetrics (DM);
- int displaywidth = Dm.widthpixels; //Width
- int displayheight = Dm.heightpixels; //Height
The information returned by the method goes beyond the virtual key section mentioned above (this part is called Decor view), but the area obtained by the method still includes the status bar. So how do you get the actual display area?
3.getWindow (). Getdecorview (). Getwindowvisibledisplayframe (Rect)
Java code
- Rect rect = new rect ();
- Activity.getwindow (). Getdecorview (). Getwindowvisibledisplayframe (rect);
The rect obtained by this method is the entire actual display area, that is, the rect.top is the height of the status bar, Screenheight-rect.bottom is the height of the bottom virtual key. When the other part of the display area is obscured (for example, when the input soft keyboard pops up), the area obtained by the method changes accordingly.
Note: The size information for all methods is px
Android Screen Information acquisition