Android app主界面基本上是一个Activity+多个Fragment来实现页面切换的,有的Fragment 需要通栏展示,有的不需要(fitsSystemWindows = true 一般是布局文件中通过fitsSystemWindows来预留状态栏的位置),如果有多个Fragment添加到Activity中显示后,有多个Fragment 设置fitsSystemWindows = true,则只有第一个Fragment的fitsSystemWindows起作用了,其他的都不会有效果,布局就会顶栏展示。
只要将多个Fragment的容器的方法重写:
public class WindowInsetsFrameLayout extends FrameLayout {
public WindowInsetsFrameLayout(Context context) {
this(context, null);
}
public WindowInsetsFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Activity 里面多个Fragment 设置fitsSystemWindows 不生效
* @param insets
* @return
*/
@Override
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
try {
if (!insets.isConsumed()) {
// each child gets a fresh set of window insets
// to consume.
final int count = getChildCount();
for (int i = 0; i < count; i++) {
WindowInsets freshInsets = new WindowInsets(insets);
getChildAt(i).dispatchApplyWindowInsets(freshInsets);
}
}
} catch (Exception e){}
return insets;
}
}