Umut
Umut

Reputation: 11

getDisplayMetrics().heightPixels isn't accurate

I have the following code:

protected void onCreate(Bundle savedInstanceState) {
//...
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
screenW = getResources().getDisplayMetrics().widthPixels;
screenH = getResources().getDisplayMetrics().heightPixels;
//...
}

getDisplayMetrics() gives for a 1024x600 screen screenW=1024 and screenH=552 This is exactly what I need, it gives only the screen excluding the status bar. But for some screens it gives the width and height of the screen including the status bar.(like screenW=1024 and screenH=600) I've tried the screens in GenyMotion and getDisplayMetrics() returned for some screens the width and the height including the statusbar and for other screens excluding the statusbar. For Samsung Galaxy S4, which has a 1080x1920 screen, it returned screenW=1920 and screenH=1080. (Here I'm aware that the display is rotated) For a tablet with a 1024x768 screen it returned screenW=1024 and screenH=720.

There are a lot of functions like

    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    getWindowManager().getDefaultDisplay().getRectSize(rectTemp);
    getWindowManager().getDefaultDisplay().getSize(p);

but all of them give for some screens the screen size including the status bar and for others excluding the status bar. But I've found that

getWindowsManager().getDefaultDisplay().getRealmetrics(metrics)

always gives the size including the statusbar.

So, what do you suggest for getting the width and the height of the screen excluding the statusbar?

Upvotes: 0

Views: 1751

Answers (1)

Antrromet
Antrromet

Reputation: 15414

If you are always getting the height of the screen including the status bar, and you want it without the status bar height, you could simply calculate the status bar height and subtract from it. To get the status bar height, you can use the following code.

public int getStatusBarHeight() {
    int statusBarHeight = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }
    return statusBarHeight;
}

Upvotes: 1

Related Questions