虽然以上所有答案都围绕着同一基本思路,你可以使用上面的其中一个示例来使其在简单布局中运作。但是我想在使用滑动“全屏幕”(标签栏除外)片段导航时更改背景颜色,并保持常规导航、选项卡和操作栏。
仔细阅读
Anton Hadutski的文章后,我对发生的事情有了更好的理解。
我有一个带有
ConstraintLayout
(即容器)的
DrawerLayout
,其中包括主要片段和
BottomNavigationView
的工具栏。
将
DrawerLayout
的
fitsSystemWindows
设置为true是不够的,您需要同时设置
DrawerLayout
和
ConstraintLayout
。假设状态栏透明,则状态栏颜色现在与
ConstraintLayout
的背景颜色相同。
但是,所包含的片段仍具有状态栏插入,因此在其上方动画另一个“全屏幕”片段并不会更改状态栏的颜色。
在参考文章中,将一小段代码放入
Activity
的
onCreate
方法中:
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
insets.replaceSystemWindowInsets(
insets.systemWindowInsetLeft,
0,
insets.systemWindowInsetRight,
insets.systemWindowInsetBottom
)
}
除了现在的工具栏没有考虑状态栏的高度之外,一切都很好。参考文章后,我们得到了一个完全可行的解决方案:
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>