在Fragment中沉浸菜单栏失效问题的记录和处理

使用了QMUI的toolbar封装了一下,然后include在每一个Fragment上,点击切换后发现沉浸式菜单栏失效。在*上面发现大佬的解答,然后一知半解,然后又看到了一位小哥哥写的解决办法。试了一下好用,所以记录一下

大佬的解答是这样的。

Your FrameLayout is not aware of window inset sizes, because it's parent - LinearLayout hasn't dispatched him any. As a workaround, you can subclass LinearLayout and pass insets to children on your own......

言归正传,原始布局是这样的

在Fragment中沉浸菜单栏失效问题的记录和处理

发现的问题是,初始直接加载的Fragment沉浸菜单栏好使的,点击按钮切换后fitsSystemWindows功能失效。查询 一番后发现是事件分发机制搞的鬼。初始加载的时候,onApplyWindowInsets能分发到FrameLayout的子控件。但是切换Fragment不会再次分发。所以我们要重新自定义一下FrameLayout就行了, 这个很简单,继承一下Framelayout,然后实现一下监听内容改变的setOnHierarchyChangeListener监听器就可以了。监听到内容改变就尝试重新dispatchWindowInsets。废话不多说,直接看代码。

class MyFrameLayout extends FrameLayout{

    public MyFrameLayout(@NonNull Context context) {
        super(context);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
    public MyFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
            @Override
            public void onChildViewAdded(View parent, View child) {
                Logger.d("onChildViewAdded");
                requestApplyInsets();
            }
            @Override
            public void onChildViewRemoved(View parent, View child) {

            }
        });
    }

    @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
    public MyFrameLayout(@NonNull Context context, @Nullable 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 super.onApplyWindowInsets(insets);
    }

}

setOnHierarchyChangeListener的监听器我在两个构造方法 都调用了,两段代码一样的。 下面的onApplyWindowInsets主要就是把这个事件重新分发到每一个子控件。这样在XML中重新引用这个MyFrameLayout 代替之前的FrameLayout就可以了。

有空我再看看这块的分发机制到底是怎么样的。感谢下面的大佬

*的大佬解答

csdn小哥哥的解答