Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android get screen size including the size of status bar and software navigation bar

How can I get the size of the screen in pixels with navigation bar and status bar being included?

I have already tried getting the size using DisplayMetrics but the size doesn't include the software navigation bar.

like image 625
EC84B4 Avatar asked Oct 31 '14 12:10

EC84B4


1 Answers

software navigation is added since API 17 (JELLY_BEAN_MR1) so we need the to include the size of navigation bar only in API 17 and above. and note that when you get the screen size it is based on the current orientation.

public void setScreenSize(Context context) {
    int x, y, orientation = context.getResources().getConfiguration().orientation;
    WindowManager wm = ((WindowManager) 
        context.getSystemService(Context.WINDOW_SERVICE));
    Display display = wm.getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        Point screenSize = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealSize(screenSize);
            x = screenSize.x;
            y = screenSize.y;
        } else {
            display.getSize(screenSize);
            x = screenSize.x;
            y = screenSize.y;
        }
    } else {
        x = display.getWidth();
        y = display.getHeight();
    }

    int width = getWidth(x, y, orientation);
    int height = getHeight(x, y, orientation);
}

private int getWidth(int x, int y, int orientation) {
    return orientation == Configuration.ORIENTATION_PORTRAIT ? x : y;
}

private int getHeight(int x, int y, int orientation) {
    return orientation == Configuration.ORIENTATION_PORTRAIT ? y : x;
}

link to gist -> here

like image 174
EC84B4 Avatar answered Sep 30 '22 16:09

EC84B4