Android obtains the screen size and density

Source: Internet
Author: User

In some cases, we need to obtain the physical size of the screen of the Android mobile phone or Pad to facilitate the interface design or other functions. The following describes how to obtain the physical size of a screen:
I have found a lot of information on the Internet and found that obtaining the screen size is not very complex programming operations. The following code can be used to obtain the screen size.
Write the following code in the onCreate method of an Activity:
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
Yes, it should be noted that on a low-density cell phone, only the code above cannot obtain the correct size. For example, if you run the above Code on a X low-density mobile phone,
The obtained screen size is 320x427. Therefore, the study found that if multi-resolution support is not set, the Android system will convert the low density (120) of x320
It is the size corresponding to the medium density (160), which greatly affects the coding of the program. Therefore, you must add
Supports-screens node. 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 way, the current Android program supports multiple resolutions, so you can get the correct physical size.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.