android gets the implementation of the screen height and width

  • 2020-06-15 10:10:48
  • OfStack

This article illustrates how android gets the height and width of the screen. Share to everybody for everybody reference. The specific analysis is as follows:

We need to get the physical size of the Android phone or Pad screen for interface design or other functions. So let's talk about lecture 1 how do you get the physical size of the screen

The following code gets the screen size.
In the onCreate method of 1 Activity, 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;  // The density of the screen DPI ( 120 / 160 / 240 )

However, it should be noted that on a low density small screen phone, the above code alone will not get the correct size. For example, a 240x320 pixel low-density phone running this code will get a screen size of 320x427. Therefore, it was found that without multi-resolution support, the Android system would convert the low-density (120) size of 240x320 to the medium-density (160) size, which would greatly affect the coding of the program. Therefore, it is necessary to add ES22en-ES23en node into the AndroidManifest. xml file of the project, and the specific content is as follows:

<supports-screens  
   android:smallScreens="true" 
   android:normalScreens="true" 
   android:largeScreens="true" 
   android:resizeable="true" 
   android:anyDensity="true" />

This way, the current Android program supports multiple resolutions, so you 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)); 
           
        // define DisplayMetrics object    
         setContentView(R.layout.main);   
         DisplayMetrics  dm = new DisplayMetrics();   
        // Get window properties    
         getWindowManager().getDefaultDisplay().getMetrics(dm);   
         
        // Window width    
         int screenWidth = dm.widthPixels;   
        
        // Window height    
         int screenHeight = dm.heightPixels;          
         TextView textView = (TextView)findViewById(R.id.tv1);          
         textView.setText(" The width of the screen : " + screenWidth + "\n Screen height: " + screenHeight);  
    } 
}

Hopefully, this article has been helpful in your Android programming.


Related articles: