Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

java - What are WindowInsets?

I am trying to learn about the Android OS and while I was reading the Google I/O 2014 app, I came across the WindowInsets. If anyone can explain what they are then it would be a great help. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...