替换 fragment 时Android适合SystemWindows不起作用

标签 android android-layout android-fragments

我有 SingleFramgnetActivity,其目的只是在其中保存和替换 fragment 。

布局如下:

<?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>

我正在替换 FrameLayout 中的 Fragments。当我在 Fragment 布局上将 fitsSystemWindows 设置为 true 时,它​​没有响应。实际上它只有在创建 Activity 时才有效,但是一旦我替换 FrameLayout 内的 FragmentfitsSystemWindows参数被忽略,布局位于状态栏和导航栏下方。

我找到了一些 solution使用使用不推荐使用的方法的自定义 FrameLayout,但由于某种原因,它对我不起作用(与普通 FrameLayout 的结果相同),我也不喜欢使用不推荐使用的方法的想法。

最佳答案

您的 FrameLayout 不知道窗口插入大小,因为它是父级 - LinearLayout 没有分派(dispatch)它。作为一种解决方法,您可以将 LinearLayout 子类化并自行将 insets 传递给子项:

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

您可以查看my this答案,它将详细解释它是如何工作的,以及如何使用 ViewCompat.setOnApplyWindowInsetsListener API。

关于替换 fragment 时Android适合SystemWindows不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307674/

相关文章:

java - 自定义对象上的数组为空

java - Android 从我的应用程序打开外部 IMDB 应用程序

Android使椭圆形背景可与聊天角一起绘制

android - 突出显示重点编辑文本

android - 如何自定义处理for Fragment的BackPressed键?

android - 从 Fragment 返回时,Flow onEach/collect 被多次调用

android - 如何在工具栏的垂直中心实现后退箭头(向上按钮)

android - 安装后删除应用程序 (*.apk)

java - 如何更改 Android 中的菜单项大小?

Android 从操作栏中删除标题栏