NavigationViewを全画面表示するとstatus barやnavigation barを透過させていても暗い色がついてしまう現象の解決法


android10対応の一環としてアプリの全画面を
https://developer.android.com/guide/navigation/gesturenav#transparent-bars
https://developer.android.com/guide/navigation/gesturenav#vis-flag
を見て対応。
status barもnavigation barもstyleから色を@android:color/transparentにして、javaからSystemUiVisibilityにView.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION、View.SYSTEM_UI_FLAG_LAYOUT_STABLE、View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREENフラグを設定し、全画面表示できるようにした。

が、NavigationViewだけは何故か上下のstaus bar部分とnavigation bar部分に影がついてしまう。

 

  • NavigationView(緑)を包むDrawerLayout(青)を広げる前と後。DrawerLayoutしか表示されていないときは上下の影は消えているし全画面表示できているが、NavigationView部分だけは影がついてしまっている。

    ※わかりやすくするためDrawerLayoutの子ViewにはNavigationViewしかもたせないようにして、広げても背景が暗くならないようにしています。
    (android10対応といいつつスクショを取るのに使った端末はandroid9の端末)

解決法

NavigationViewにapp:insetForeground属性を付けてやる。

before

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#afeeee"
        android:fitsSystemWindows="false">

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="left"
            android:background="#00ff00"
            android:fitsSystemWindows="false"/>


    </androidx.drawerlayout.widget.DrawerLayout>

</layout>

after

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#afeeee"
        android:fitsSystemWindows="false">

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_gravity="left"
            android:background="#00ff00"
            android:fitsSystemWindows="false"
            app:insetForeground="@android:color/transparent" />


    </androidx.drawerlayout.widget.DrawerLayout>

</layout>

  • DrawerLayoutを広げてNavigationViewが表示されても上下の影が表示されず、全画面表示に対応できてる!

なぜ?

NavigationViewはScrimInsetsFrameLayoutのサブクラスであり、こいつは端末のstatus barやnavigation barの高さの部分をapp:insetForegroundで指定した色で塗るかららしい。(http://y-anz-m.blogspot.com/2015/06/scriminsetsframelayout-androidbackground.html)