Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getWindowVisibleDisplayFrame() gives different values in Android 2.2, 2.3 (but not 2.3.3)

I've got an Activity which uses

getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);

to determine the useable screen space and decide where to place images.

Returning to the Activity after I click the hardware "back" button to leave the Activity, the rectangle values are

(0,0,800,480)

However, returning to the Activity after I click the hardware "home" button to leave the Activity, the rectangle values are

(0,38,800,480)

which throws off the display and the image placement.

How can I ensure I get a consistent values when calling

getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);

no matter how I left the app?

UPDATE: Thanks to @Reno for helping test; it seems to be dependent on Android version than the device.

like image 341
Thunder Rabbit Avatar asked Oct 05 '11 10:10

Thunder Rabbit


3 Answers

Welp, if you read the comments in the source, it admits that this method is kind of broken

    public void getWindowVisibleDisplayFrame(Rect outRect) {
    if (mAttachInfo != null) {
        try {
            mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
        } catch (RemoteException e) {
            return;
        }
        // XXX This is really broken, and probably all needs to be done
        // in the window manager, and we need to know more about whether
        // we want the area behind or in front of the IME.
        final Rect insets = mAttachInfo.mVisibleInsets;
        outRect.left += insets.left;
        outRect.top += insets.top;
        outRect.right -= insets.right;
        outRect.bottom -= insets.bottom;
        return;
    }

You will have to ignore the outRect.top value for versions < 2.3.3

like image 110
Reno Avatar answered Sep 30 '22 20:09

Reno


here is a link to get status bar directly instead of calculate it. It will avoid any issue of getWindowVisibleDisplayFrame which is really inconsistent through platforms and devices.

like image 43
superuser Avatar answered Sep 30 '22 21:09

superuser


There are times when you need to know the precise dimensions of the available space for a layout when in an activity's onCreate. After some thought I worked out this way of doing it: https://stackoverflow.com/a/16691531/2202013 It does not use getWindowVisibleDisplayFrame and is hopefully future proof.

like image 37
Steve Waring Avatar answered Sep 30 '22 19:09

Steve Waring