最近遇到一个奇葩问题,导航栏多个Fragment沉浸,fitsSystemWindows = true只在一个Fragment有效,其他Fragment都是无效的(即:toolbar和状态栏重叠)

这种问题产生的原因:当第一个Fragment添加到Activity中的时候,Activity寻找出有fitsSystemWindows的子布局为其预留出状态栏的空间,其实就是设置一个padding,而其他Fragment添加到Activity中的时候,因为状态栏空间的适配已经被消费过一次了,Activity并不会再次去添加这个padding。因此我们需要自定义一个FrameLayout,重写它的状态栏空间适配的时机和它的适配事件的分发。

经过一系列翻查,测试,最终找到了一种合适的处理方案,废话不多说一起来看一下吧!

public class WindowInsetsFrameLayout extends FrameLayout {

public WindowInsetsFrameLayout(Context context) {

this(context, null);

}

public WindowInsetsFrameLayout(Context context, AttributeSet attrs) {

this(context, attrs, 0);

}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)

public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

setOnHierarchyChangeListener(new OnHierarchyChangeListener() {

@Override

public void onChildViewAdded(View parent, View child) {

requestApplyInsets();

}

@Override

public void onChildViewRemoved(View parent, View child) {

}

});

}

@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);

return insets;

}

}

因为Fragment是添加到FrameLayout这个容器的,我们给他设置一个布局层次结构改变的监听,当Fragment被添加进去的时候,通过requestApplyInsets()方法使Activity重新进行一次状态栏空间的适配,因为FrameLayout中还有其他的Fragment,我们还需要重写onApplyWindowInsets方法,对其子View进行遍历,逐个分发状态栏空间的适配事件。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐