LoginSignup
4
1

More than 5 years have passed since last update.

画面によってstatus barの色を変える方法(Android JetPack / Navigation)

Posted at

はじめに

画面によってstatus barの色を変える方法です。
Android JetPackのNavigationを使っている場合にフォーカスして記載します。
Navigationは1.0.0-alpha05を使用しています。
イメージはこんな感じです。
sample.gif

サンプルに使用した元のアプリはNavigationのcodelabのものを使わせていただきました。
https://github.com/googlecodelabs/android-navigation

対応方法

順を追って説明しますが、対応手順は3つです。

1.ステータスバーの色定義

やり方は色々あるかと思いますが、整理しやすいようにここではステータスバーの色をenumで定義しました。

StatusBarColor.kt
enum class StatusBarColor(private val key: String, val color: Int) {
    BLUE("blue", android.R.color.holo_blue_dark),
    RED("red", android.R.color.holo_red_dark),
    BLACK("black", android.R.color.black);

    companion object {
        fun findByKey(key: String?): StatusBarColor =
                StatusBarColor.values().find { it.key == key } ?: BLACK
    }
}

findByKeyは、引数はnullableで、戻り値はnon-nullにした方が後々便利です。

2.各Fragmentにステータスバーの色を定義

Navigationのxmlにおいて、各Fragmentのargumentにステータスバーの色情報を与えます。コード上でこれを参照して、ステータスバーの色を変えます。

mobile_navigation.xml
<navigation ...>
    <fragment ...>
        <argument
            android:name="statusBarColor"
            android:defaultValue="blue"
            app:argType="string" />
        ...
    </fragment>
    <fragment ...>
        <argument
            android:name="statusBarColor"
            android:defaultValue="red"
            app:argType="string" />
        ...
    </fragment>
    ...
</navigation>
  • android:name : コード上でargumentから値を取り出すときに使います
  • android:defaultValue : 先ほど定義したStatusBarColorkeyを指定します
  • app:argType : 文字列(string)として定義します。先頭の「s」は小文字なのでご注意を。

3.NavControllerにリスナー設定

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...()
    findNavController(R.id.my_nav_host_fragment).addOnNavigatedListener { _, destination ->
        // argumentからstatus barの色情報を取得する
        val statusBarColor = StatusBarColor.findByKey(destination.defaultArguments.getString("statusBarColor"))
        // status barの色を変更
        window.statusBarColor = ContextCompat.getColor(this, statusBarColor.color)
    }
}

NavControllerに対してOnNavigatedListenerを設定します。これにより、Navigationでの画面遷移完了時に通知を受け取ることができます。その際、引数でNavDestinationが受け取れます。このNavDestinationは画面遷移したFragmentの情報を持っており、ここに上で定義したargumentも含まれています。

よって、このdestinationからdefaultArguments.getStringでString値を取り出し、StatusBarColorへと変換します。
このとき、string値がnullだったり、argumentに定義がなかったりした場合でも、StatusBarColor.findByKeyの引数がnullableで戻り値がnonnullだと、便利に使えます。

あとは、StatusBarColorのcolorResIdを使って実際にステータスバーの色を変えるだけで完了です。

関連リンク

Navigationでバックキーをハンドリングする

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1