Hello everyone, This section describes how Android gets the screen size of a mobile phone. This section mainly uses three objects.
Textview ,
Button , And
Displaymetrics , Where
Displaymetrics Is the Key class for getting the phone screen size. This example is very simple. When we click the button to trigger the event
Textview Display the width and resolution of the mobile phone screen.
Take a look:
Before the button is triggered:
After the button is triggered:
Here, we add the following two lines in res-> Layout-> values-> string. XML (in bold)
<? XML version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "hello"> Hello world, displaymetricsdemo! </String>
<String name = "app_name"> displaymetricsdemo </string>
<String name = "resolution"> mobile phone resolution: </string>
<String name = "pressme"> resolution obtained by me </string>
</Resources>
The layout file main. xmlCodeAs follows:
<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Textview
Android: Id = "@ + ID/textview1"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/Resolution"
/>
<Button
Android: Id = "@ + ID/button1"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/pressme"
/>
</Linearlayout>
Finally, the main class displaymetricsdemo. Java has the following code:
Package com. Android. test;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. util. displaymetrics;
Import Android. View. view;
Import Android. widget. Button;
Import Android. widget. textview;
Public class displaymetricsdemo extends activity {
Private textview textview1;
Private button button1;
// Obtains the cell phone screen resolution.
Private displaymetrics DM;
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
// Obtain the textview and button objects in the layout.
Textview1 = (textview) findviewbyid (R. Id. textview1 );
Button1 = (button) findviewbyid (R. Id. button1 );
// Add a button Event Response
Button1.setonclicklistener (New button. onclicklistener (){
Public void onclick (view V)
{
Dm = new displaymetrics ();
Getwindowmanager (). getdefaultdisplay (). getmetrics (DM );
// Obtain the phone's bandwidth and height in pixels.
String STR = "cell phone screen resolution:" + DM. widthpixels
+ "*" + DM. heightpixels;
Textview1.settext (STR );
}
});
}
}
This example is relatively simple. The core is the several lines of code in onclick. This section ends here! Thank you ~