Status Barを自動的にToolbarと同じ色に変える

CoordinatorLayout -> AppBarLayout -> MaterialToolbar

<androidx.coordinatorlayout.widget.CoordinatorLayout
        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:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <com.google.android.material.appbar.MaterialToolbar
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
...

目次

テーマでStatus Barを透明にしてしまう

これをしないと、colorPrimaryDarkの色になります。

<item name="android:statusBarColor">@android:color/transparent</item>

スタイルにfitsSystemWindowsを設定する

直接テーマに設定しても効きませんので、適用させるスタイルを作ります。

<style name="CoordinatorLayout">
    <item name="android:fitsSystemWindows">true</item>
</style>

<style name="AppBarLayout" parent="Widget.MaterialComponents.AppBarLayout.Primary">
    <item name="android:fitsSystemWindows">true</item>
</style>

テーマにまとめる

これで、ステータスバーとツールバーの色は共にcolorPrimaryになります。

ツールバーが必要な時はCoordinatorLayoutAppBarLayoutを使うと言う縛りが生まれますが、ステータスバー自体が透明なので、他の画面にもテーマを拡張させやすくなります。

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="coordinatorLayoutStyle">@style/CoordinatorLayout</item>
    <item name="appBarLayoutStyle">@style/AppBarLayout</item>
</style>

入力画面の場合は要注意

この方法は、windowSoftInputModeadjustResizeの場合にBottomNavigationViewが最上部までせり上がってしまう深刻な問題があります。じゃあ使えないわって方が多いかも。。。