Get screen width and height in Android

前端 未结 30 4141
野的像风
野的像风 2020-11-22 09:28

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, \"onM         


        
30条回答
  •  眼角桃花
    2020-11-22 10:21

    Just use the function below that returns width and height of the screen size as an array of integers

    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 your onCreate function or button click add the following code to output the screen sizes as shown below

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

提交回复
热议问题