有多少个 WindowInsets?

How many WindowInsets are there?

我不了解 WindowInsets 矩形,因为文档说:

The system window inset represents the area of a full-screen window that is partially or fully obscured by the status bar, navigation bar, IME or other system windows.

因此,可以有多个 WindowInsets,每个都有自己的矩形(一个用于状态栏,另一个用于导航栏......),我如何检索它们?

或者只有一个 WindowInsets 并且它的左上右下坐标是应用可用 window 的矩形?

WindowInsets 描述了 window 内容的一组插图。 换句话说,WindowInsets 具有应用程序可用区域的一个矩形(并且具有其他信息,如 isRound)。可用区域不包括 StatusBarNavigationBar.

的矩形

如果您只想知道 StatusBarNavigationBar 的身高,请检查 this

你可以像下面这样得到WindowInsets。 以下示例使用 WindowInsetsCompat 来实现兼容性。

在你的 style.xml:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    ...
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

在你的AndroidManifest.xml

<application
        ...
        android:theme="@style/AppTheme">

        ...

</application>

在您的布局中xml:(应设置 fitsSystemWindows 以获取 WindowInsets。)

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

    <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</FrameLayout>

在您的Activity(或任何地方):

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View container = findViewById(R.id.container);

        ViewCompat.setOnApplyWindowInsetsListener(container, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {

                //you can do something with insets.
                int statusBar = insets.getSystemWindowInsetTop(); //this is height of statusbar
                int navigationBar = insets.getStableInsetBottom(); //this is height of navigationbar
                Log.d("MainActivity", String.format("%s %s", statusBar, navigationBar));

                ViewCompat.onApplyWindowInsets(v, insets);
                return insets;
            }
        });
    }
}

WindowInsets 是这样的:

只有一种 WindowInsets 描述了 window 内容的一组插图。因为它是不可变的,将来可能会扩展以包含更多的插入类型。您可以创建它的更多实例。您还可以使用 getStableInsetBottom() 等方法以像素为单位获取 WindowInsets 的左、右等插图