首页 > 解决方案 > 当屏幕强制旋转时,WindowInsets 总是返回 0

问题描述

当我得到宽度和高度的屏幕尺寸时,我以前使用WindowManager().getDefaultDisplay().getMetrics(metrics)过,这是下面的整个代码。

DisplayMetrics metrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(metrics);
usableHeight = metrics.heightPixels;
usableWidth = metrics.widthPixels;

在 Android 11中,getDefaultDisplay().getMetrics(metrics)已弃用。
所以我找到了“WindowInsets”,它在屏幕显示时运行良好。
当屏幕从纵向到纵向或从横向到横向时,它也能很好地工作。
但有一个问题。当我强行将屏幕从纵向旋转到横向时,WindowInsets无法获得准确的当前显示尺寸。
详细地说,它是 3 步。

1. 启动应用程序。

2.应用一启动,屏幕就强制从纵向转为横向。

3. WindowInsets 无法获取Insets.rightand Insets.left

这是获取显示大小的整个代码。

private static int getDisplaySize(WindowManager wm, boolean wantWidth) {
    int usableHeight = 0;
    int usableWidth = 0;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics metrics = wm.getCurrentWindowMetrics();
        WindowInsets windowInsets = metrics.getWindowInsets();
        Insets insets = windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());

        int insetsWidth = 0;
        int insetsHeight = 0;
        if (insets != null) {
            insetsWidth = insets.right + insets.left;
            insetsHeight = insets.top + insets.bottom;
        }
        Size realSize = new Size(0, 0);
        if (metrics.getBounds() != null) {
            Rect bounds = metrics.getBounds();
            realSize = new Size(bounds.width() - insetsWidth, bounds.height() - insetsHeight);
        }
        usableWidth = realSize.getWidth();
        usableHeight = realSize.getHeight();
    } else {
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        usableHeight = metrics.heightPixels;
        usableWidth = metrics.widthPixels;
    }

    return wantWidth ? usableWidth : usableHeight;
}

屏幕旋转后如何获得Insets.rightand ?Insets.left

另外
,我发现了一些线索。请检查以下内容。

  1. 当我再次启动应用程序时,它会获得正确的值(宽度,高度),但当我第一次启动应用程序时它不能。

  2. 在第二次,我关闭应用程序并触摸主屏幕,然后重新启动应用程序,它无法获得正确的宽度和高度。

  3. 如果您不触摸或拖动主屏幕,即使关闭应用程序,您也可以获得正确的宽度、高度。

所以它运行得很奇怪。

标签: androidandroid-layoutandroid-windowmanagerandroid-11windowinsets

解决方案


推荐阅读