替换片段时,Android fitsSystemWindows无法正常工作

San*_*dak 18 android android-layout android-fragments

SingleFramgnetActivity的目的只是保持和替换其中的碎片.

布局看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".SingleFragmentActivity"
    >

    <include layout="@layout/toolbar"/>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我正在替换FragmentsFrameLayout内部.当我fitsSystemWindowsFragment布局上将其设置为true时,它没有响应.实际上它只在Activity创建时才起作用,但是一旦我更换了Fragment内部FrameLayout,fitsSystemWindows就会忽略该参数,并且布局位于状态栏和导航栏下方.

我找到了一些自定义FrameLayout的解决方案,它使用了弃用的方法,但由于某种原因它不适用于我(与普通FrameLayout相同的结果),我也不喜欢使用弃用方法的想法.

azi*_*ian 10

FrameLayout不知道窗口嵌入大小,因为它是父级 - LinearLayout没有发送任何内容.作为一种变通方法,您可以自己子类化LinearLayout并将插件传递给子节点:

@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;
}
Run Code Online (Sandbox Code Playgroud)

您可以查看我的答案,其中将详细说明其工作原理,以及如何使用ViewCompat.setOnApplyWindowInsetsListenerAPI.