Get screen height and width in Android

Source: Internet
Author: User

Sometimes we need to get the height and width of the current screen, just write the following code in an activity's OnCreate () method:

1 //Defining Displaymetrics Objects2Displaymetrics metric =NewDisplaymetrics (); 3 //Get Window Properties4 Getwindowmanager (). Getdefaultdisplay (). Getmetrics (Metric); 5 intwidth = metric.widthpixels;//screen width (pixels)6 intHeight = metric.heightpixels;//screen height (pixels)7 floatdensity = metric.density;//screen Density (0.75/1.0/1.5)8 intdensitydpi = metric.densitydpi;//screen density dpi (120/160/240)

See other blogs that on a low-density small screen 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:

1 <supports-screens  2     android:smallscreens= "true"  3     Android:normalscreens= "true"  4     android:largescreens= "true"  5     Android : Resizeable= "true"  6     android:anydensity= "true"/>  

In this case, the current Android program supports a variety of resolutions, so you can get the correct physical size.

There are two ways to get the width and height of the screen, but the method is obsolete, but you can also use:

1, WindowManager wm = (WindowManager) getcontext ()                    . Getsystemservice (Context.window_service);       int width = wm.getdefaultdisplay (). getwidth ();      int height =this. Getwindowmanager ();       int width = wm.getdefaultdisplay (). getwidth ();      int height = wm.getdefaultdisplay (). GetHeight ();

Get screen height and width in Android

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.