getWindowVisibleDisplayFrame()在Android 2.2,2.3中给出了不同的值(但不是2.3.3)

时间:2011-10-05 10:04:32

标签: android android-activity

我有Activity使用

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

确定可用的屏幕空间并决定放置图像的位置。

点击硬件“后退”按钮离开Activity后返回活动,矩形值为

(0,0,800,480)

但是,点击硬件“主页”按钮离开Activity后返回活动,矩形值为

(0,38,800,480)

会抛出显示和图像放置。

如何确保在调用

时获得一致的值
getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);

无论我如何离开应用程序?

更新:感谢@Reno帮助测试;它似乎依赖于Android版本而非设备。

4 个答案:

答案 0 :(得分:4)

Welp,如果你阅读了源代码中的评论,就会承认这种方法有点破碎

    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;
    }

您必须忽略版本的outRect.top值< 2.3.3

答案 1 :(得分:1)

here是直接获取状态栏的链接,而不是计算它。它将避免任何通过平台和设备实际上不一致的getWindowVisibleDisplayFrame问题。

答案 2 :(得分:0)

所以,我这样做了:

    Rect rectangle = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
    if(android.os.Build.VERSION.SDK_INT < 9  /* android.os.Build.VERSION_CODES.GINGERBREAD */ ) {
        // http://stackoverflow.com/questions/7659652/getwindowvisibledisplayframe-gives-different-values-in-android-2-2-2-3-but-no/7660204#7660204
        rectangle.top = 0;
    }

答案 3 :(得分:0)

有些时候,您需要在活动的onCreate中了解布局的可用空间的精确尺寸。 经过一番思考后,我采用了这种方式:https://stackoverflow.com/a/16691531/2202013 它不使用getWindowVisibleDisplayFrame,希望将来可以证明。