How to get screen width and height

后端 未结 14 1027
梦如初夏
梦如初夏 2020-12-12 20:31

I tried to use following code to get screen width and height in android app development:

Display display = getWindowManager().getDefaultDisplay(); 
int scree         


        
相关标签:
14条回答
  • 2020-12-12 20:55
    Display display = getActivity().getWindowManager().getDefaultDisplay(); 
    int screenWidth = display.getWidth();
    int screenHeight = display.getHeight();
    Log.d("Tag", "Getting Width >> " + screenWidth);
    Log.d("Tag", "Getting Height >> " + screenHeight);
    

    This worked properly in my application

    0 讨论(0)
  • 2020-12-12 20:56
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    int height = metrics.heightPixels;
    int width = metrics.widthPixels;
    

    i guess the code which you wrote is deprecated.

    0 讨论(0)
  • 2020-12-12 20:57

    Alternative way using function

    private int[] getScreenSIze(){
            DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int h = displaymetrics.heightPixels;
            int w = displaymetrics.widthPixels;
    
            int[] size={w,h};
            return size;
    
        }
    

    on button click or on your create function add the following code

    int[] screenSize= getScreenSIze();
            int width=screenSize[0];
            int height=screenSize[1];
            screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);
    

    See demo source code

    0 讨论(0)
  • 2020-12-12 21:03
    WindowManager w = getWindowManager();
    Display d = w.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    d.getMetrics(metrics);
    
    Log.d("WIDTH: ", String.valueOf(d.getWidth()));
    Log.d("HEIGHT: ", String.valueOf(d.getHeight()));
    
    0 讨论(0)
  • 2020-12-12 21:03
        int scrWidth  = getWindowManager().getDefaultDisplay().getWidth();
        int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
    
    0 讨论(0)
  • 2020-12-12 21:06
           /*
            *DisplayMetrics: A structure describing general information about a display, such as its size, density, and font scaling.
            * */
    
     DisplayMetrics metrics = getResources().getDisplayMetrics();
    
           int DeviceTotalWidth = metrics.widthPixels;
           int DeviceTotalHeight = metrics.heightPixels;
    
    0 讨论(0)
提交回复
热议问题