WindowInsets
是应用于窗口的系统视图(例如状态栏、导航栏)的插图(或大小)。
通过具体例子就很容易理解了。想象一下这个场景:
现在,你不想WindowInsets
应用于背景ImageView
,因为在这种情况下ImageView
将由状态栏高度填充。
但您确实希望将插图应用于Toolbar
,因为否则Toolbar
将被绘制在状态栏中间的某个位置。
该视图表明了申请的愿望WindowInsets
在 xml 中这样说:
android:fitsSystemWindows="true"
在此示例中,您不能应用WindowInsets
到根布局,因为根布局会消耗WindowInsets
,以及ImageView
将被填充。
相反,你可以使用ViewCompat.setOnApplyWindowInsetsListener
将插图应用到工具栏:
ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, insets) -> {
((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin =
insets.getSystemWindowInsetTop();
return insets.consumeSystemWindowInsets();
});
请注意,当Toolbar
的根布局传递WindowsInsets
给它的孩子。布局如FrameLayout
, LinearLayout
不要,DrawerLayout
, CoordinatorLayout
do.
您可以对布局进行子类化,例如FrameLayout
并覆盖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;
}
有一个不错的博客文章在medium伊恩·莱克 (Ian Lake) 也谈到了这个问题“成为窗户安装大师
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)