虽然上述所有答案都围绕着相同的基本思想,但您可以使用上述示例之一使其与简单布局一起使用。但是,我想在使用滑动“全屏”(标签栏旁边)片段导航时更改背景颜色,并保持常规导航、标签和操作栏。
仔细阅读an article by Anton Hadutski后,我更好地了解了这是怎么回事。
我有DrawerLayout 和ConstraintLayout(即容器),其中有Toolbar,包括主要片段和BottomNavigationView。
将DrawerLayout 设置为将fitsSystemWindows 设置为true 是不够的,您需要同时设置DrawerLayout 和ConstraintLayout。假设状态栏是透明的,现在状态栏颜色和ConstraintLayout的背景颜色一样。
但是,包含的片段仍然插入了状态栏,因此在 with 顶部设置另一个“全屏”片段的动画不会改变状态栏的颜色。
引用文章中的一段代码到Activity的onCreate:
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft,
0,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom
)
}
一切都很好,除了现在Toolbar 没有解决状态栏高度。更多参考这篇文章,我们有一个完整的解决方案:
val toolbar = findViewById<Toolbar>(R.id.my_toolbar)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
val params = toolbar.layoutParams as ViewGroup.MarginLayoutParams
params.topMargin = insets.systemWindowInsetTop
toolbar.layoutParams = params
insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft,
0,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom
)
}
main_activity.xml(请注意Toolbar中的marginTop是为了预览,会被代码代替):
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintTop_toTopOf="@id/container"
android:layout_marginTop="26dp"
android:background="@android:color/transparent"
...>
...
</androidx.appcompat.widget.Toolbar>
<include layout="@layout/content_main" />
...
</androidx.constraintlayout.widget.ConstraintLayout>
...
</androidx.drawerlayout.widget.DrawerLayout>