有多少WindowInsets?

GPa*_*ack 16 android android-view android-windowmanager

我不了解WindowInsets rects,因为docs说:

系统窗口插图表示全屏窗口的区域,该区域被状态栏,导航栏,IME或其他系统窗口部分或完全遮盖.

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

或者是有只有一个WindowInsets和它的左顶右底坐标是该应用的可用窗口的矩形?

nsh*_*ura 8

WindowInsets描述了窗口内容的一组插入.换句话说,WindowInsets有一个应用程序可用区域的矩形(并有其他信息isRound).可用区域排除的RECT StatusBarNavigationBar.

如果你只是想知道的高度StatusBarNavigationBar,检查这个.

你可以得到WindowInsets如下.以下示例使用WindowInsetsCompat来实现兼容性.

在你的style.xml中:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    ...
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>
Run Code Online (Sandbox Code Playgroud)

在你的AndroidManifest.xml中

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

        ...

</application>
Run Code Online (Sandbox Code Playgroud)

在你的布局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>
Run Code Online (Sandbox Code Playgroud)

在您的活动(或任何地方):

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;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

WindowInsets是这样的:

在此输入图像描述