我有 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
内的 Fragment
,fitsSystemWindows
参数被忽略,布局位于状态栏和导航栏下方。
我找到了一些 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/