What are WindowInsets?

我怕爱的太早我们不能终老 提交于 2019-11-26 19:45:59

You can learn all about WindowInsets here. WindowInsets provides you with the area on the window that is usable by the application. By itself it's of not much use. It's true purpose comes when you either override View.onApplyWindowInsets or implement View.OnApplyWindowInsetsListener. You can read about them here: View.onApplyWindowInsets and View.OnApplyWindowInsetsListener

Listener for applying window insets on a view in a custom way.

Apps may choose to implement this interface if they want to apply custom policy to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener is set, its onApplyWindowInsets method will be called instead of the View's own onApplyWindowInsets method. The listener may optionally call the parameter View's onApplyWindowInsets method to apply the View's normal behavior as part of its own.

In short, overriding this will let you control area of the window available for your View.

WindowInsets are insets (or sizes) of system views (e.g. status bar, navigation bar), that are applied to the window.

It would be easy to understand on concrete example. Image this scenario:

Now, you don't want WindowInsets to be applied to the background ImageView, because in that case the ImageView would be padded by status bar height.

But you do want insets to be applied to Toolbar, because otherwise Toolbar would be drawn somewhere mid status bar.

The view declares a desire to apply WindowInsets in xml by saying:

android:fitsSystemWindows="true"

In this example you cannot apply the WindowInsets to the root layout, because the root layout would consume WindowInsets, and the ImageView would be padded.

Instead you may use ViewCompat.setOnApplyWindowInsetsListener to apply insets to toolbar:

ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, insets) -> {
            ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin =
                    insets.getSystemWindowInsetTop();
            return insets.consumeSystemWindowInsets();
        });

Note, this callback would be called, when Toolbar's root layout passes WindowsInsets to its children. Layouts like FrameLayout, LinearLayout do not, DrawerLayout, CoordinatorLayout do.

You can subclass your layout, e.g. FrameLayout and override onApplyWindowInsets:

@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
    int childCount = getChildCount();
    for (int index = 0; index < childCount; index++)
        getChildAt(index).dispatchApplyWindowInsets(insets); // let children know about WindowInsets

    return insets;
}

There's a nice blog post at medium by Ian Lake concerning this stuff, also "Becoming a master window fitter🔧" presentation by Chris Banes.

I've also created a detailed article at Medium concerning WindowInsets.

More resources:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!