Search code examples
androidheightpixelandroid-statusbar

Does getSize() in Android include the height of the status bar?


Is there a way to tell if getSize() includes the height of the status bar? From testing on a few different phones it seems it does on some but not on others and it is frustrating when trying to make everything in the layout line up properly.

After spending a week on this problem and checked Google's documentation & many other posts here on Stackoverflow (about getting the screen size in pixels via getSize(), getRealSize(), getMetrics(DisplayMetrics metrics), getRealMetrics(DisplayMetrics metrics), etc ... I still have no clue about it.

This picture is giving a better picture of the problem.

On some phones and according to the above picture, the line 'Y/2' should be exactly at size.y / 2 (exact half of the screen between the navigation & the status bars), but is actually not in the middle : The 'Not X' distance on my picture is therefore equal to 'X - getStatusBarSize()'.

I have to add that i am using a ring object with an innerRadiusRatio 2.1 in XML. But i don't think it's the reason because once i am using the code below, it works on phones where getSize() seems to include the height of the status bar :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Screen dimensions
        display = getWindowManager().getDefaultDisplay();
        size = new Point();
        display.getSize(size);

       //Get the screen dimensions
       maxWidth = size.x 
       maxHeight = size.y - getStatusBarSize();
   }

private int getStatusBarSize() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }

While it works simply with maxheight = size.y on others phones (where it does not include the status bar height).

Thanks in advance guys for any help !


Solution

  • I was facing to the same issue more or less and this could be helpful :

    // Get the size between the status & the navigation bars
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    
    // Real size of the screen (full screen)
    Point realSize = new Point();
    Display realDisplay = getWindowManager().getDefaultDisplay();
    realDisplay.getRealSize(realSize);
    
    //Get the screen dimensions
    maxWidth = size.x;
    maxHeight = size.y;
    
    if (realSize.y - getNavBarSize() == size.y || realSize.y == size.y) {
        Log.d(TAG, "onCreate: getSize() includes the status bar size");
        maxHeight = size.y - getStatusBarSize();
    }