Get the phone screen size
Displaymetrics
Example
When developing mobile apps, in addition to the underlying understanding of the API, the most important thing is the concept of screen resolution. Because mobile phone manufacturers use different screen sizes,
The presentation and layout of user UI interfaces are naturally different.
Although android can be set to adjust the zoom ratio with the window size, even so,
Mobile phone programmers still need to know the border of the mobile phone screen to avoid layout deformation caused by scaling. This example is very short.
A few lines of code are required to obtain the resolution of the mobile phone. The key is the displaymetrics application.
Displaymetrics objects under Android. util record some common information, including display information, size, dimension, Font, and so on;
Remember to reference Android. util. displaymetrics when using it.
It is worth mentioning that the widthpixels and heightpixels fields in the displaymetrics object are of the integer type,
In the following programs, the string type is not converted. Because of the String concatenation operator, the output stropt is a string.
Package IRDC. ex03_05;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. util. displaymetrics;
Import Android. widget. textview;
Public class ex03_05 extends Activity
{Private textview mtextview01;
/** Called when the activity is first created .*/
@ Override public void oncreate (bundle savedinstancestate)
{
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
/* Android. util. displaymetrics must be referenced */
Displaymetrics dm = new displaymetrics ();
Getwindowmanager (). getdefaultdisplay (). getmetrics (DM );
String stropt = "cell phone screen resolution:" +
DM.Widthpixels + "×" + DM. heightpixels ;
Mtextview01 = (textview) findviewbyid (R. Id. mytextview01 );
Mtextview01.settext (stropt );
}
}
Extended learning
The displaymetrics object (DM in the program) created at the beginning of the program does not need to pass any parameters (during construction ),
However, after getwindowmanager () is called, the window handle of the existing activity is obtained,
In this case, call the getdefadisplay display method to store the obtained width and height dimensions in the displaymetrics object DM,
The obtained width and height dimensions are measured in pixels. "pixels" refer to "absolute pixels" rather than "relative pixels ".