LollipopでActionBarの色が変更できない
掲題の問題にはまってので、解決するまでのメモ。
やりたいこと
ThemeおよびStyleを使用してActionBarの色を変更する。
下記サイトの現象が再現するか試してみたかった。
試したこと
まずはApplicationにMyAppThemeを設定。
<!-- Base application theme. --> <style name="MyAppTheme" parent="Theme.AppCompat.Light"> <!-- Customize your theme here. --> <item name="android:actionBarStyle">@style/MyActionbarStyle</item> </style> <style name="MyActionbarStyle" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse"> <item name="android:background">@drawable/actionbar_background</item> <item name="android:textColor">@android:color/white</item> </style>
これで色は変わらず。
次に考えたのは、Emulator環境はNexus 5だったので、Material designに対応していないことが原因では?ということ。
https://developer.android.com/training/material/theme.html
(こちらのCustomize the Status Barの項参照。)
res/配下にvalues-v21フォルダを作成してstyles.xmlを追加します。
<style name="MyAppTheme" parent="@style/Theme.AppCompat.Light"> <item name="android:colorPrimary">@color/primary</item> </style>
これでも色は変わらず。
何が悪かったかというと、ThemeがTheme.AppCompatを継承していること。
AndroidStudioでBlankなActivityをつくると勝手にActionBarActivityを継承しており、
Theme.AppCompatを使う必要があるように見える。
Theme.AppCompatはSupport Libraryであり、Android Frameworkのattributeを設定しても効いてくれない。
というわけで、下記のように書くのが正解。
<style name="MyAppTheme" parent="@style/Theme.AppCompat.Light"> <item name="colorPrimary">#3F51B5</item> <item name="colorPrimaryDark">#303F9F</item> <item name="colorAccent">#E91E63</item> </style>