0

I want to calculate the total device width and height. I have a device 600x1024 and the following code shows only 552 width when landscape and 972 height portrait.

DisplayMetrics displayMetrics = new DisplayMetrics();  
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);  
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
Nick
  • 2,818
  • 5
  • 42
  • 60

1 Answers1

0

You are getting smaller size because the navigation bar takes some space, and getWindowManager().getDefaultDisplay().getMetrics(displayMetrics) will return only available screen size.

There is no official-documented way to get the full screen size, however there are some workarounds:

  1. You can get the screen size after your acticity enters full-screen mode. This should hide the navbar.
  2. You can get the size of the navbar and add it to the screen size you got in your code:

    Resources resources = context.getResources();
    int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
        return resources.getDimensionPixelSize(resourceId);
    }
    return 0;
    
  3. You can get the whole screen size:

    public static Point getRealScreenSize(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
    
        if (Build.VERSION.SDK_INT >= 17) {
            display.getRealSize(size);
        } else if (Build.VERSION.SDK_INT >= 14) {
            try {
                size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
                size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {}
        }
    
        return size;
    }
    

Methods 2 and 3 are hacks, so keep in mind that they have a chance to fail on some devices.

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52