we need to get the physical size of the screen of the Android phone or pad for the design of the interface or the implementation of other functions. Let's talk about how to get the physical size of the screen
The following code gets the size of the screen.
In an activity's OnCreate method, write the following code:
Displaymetrics metric = new Displaymetrics ();
Getwindowmanager (). Getdefaultdisplay (). Getmetrics (Metric);
int width = metric.widthpixels; Screen width (pixels)
int height = metric.heightpixels; Screen height (pixels)
float density = metric.density; Screen Density (0.75/1.0/1.5)
int densitydpi = metric.densitydpi; Screen density dpi (120/160/240)
However, it should be noted that on a low-density small-screen mobile phone, only the above code is not able to get the correct size. For example, a 240x320 pixel low-density mobile phone, if you run the above code, the screen size obtained is 320x427. As a result, the study found that without multi-resolution support, the Android system would convert the 240x320 low-density (120) size to a medium-density (160) dimension, which would greatly affect the coding of the program. Therefore, it is necessary to add the Supports-screens node in the project's Androidmanifest.xml file, the specific content is as follows:
<supports-screens
Android:smallscreens= "true"
Android:normalscreens= "true"
Android:largescreens= "true"
Android:resizeable= "true"
Android:anydensity= "true"/>
In this case, the current Android program supports a variety of resolutions, so you can get the correct physical size.
------------------------------
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.DisplayMetrics;
Import Android.widget.TextView;
public class Textcanvasactivity extends Activity {
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (New MyView (this));
Defining Displaymetrics Objects
Setcontentview (R.layout.main);
Displaymetrics dm = new Displaymetrics ();
Get Window Properties
Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);
Width of window
int screenwidth = Dm.widthpixels;
Window height
int screenheight = Dm.heightpixels;
TextView TextView = (TextView) Findviewbyid (R.ID.TV1);
Textview.settext ("screen width:" + screenwidth + "\ n Screen Height:" + screenheight);
}
}
Get screen width and height