こんばんは。普段業務と個人で Android をゴリゴリ書いています。
今回、Toolbar の icon を白くしようとして少しハマったのでその備忘録です。
かなり限定的な場面で使用するので需要はそんなにないかと思いますが、同じ場面ではまった方の力になれば幸いです。
アプリの設定
AndroidManifest.xml
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
style.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
上記のコードを見ていただければわかるのですが、ActionBar 無しのテーマを全体に適用し、構成しています。
使用しているのは Theme.AppCompat.Light.NoActionBar
ですので、文字の色とアイコンの色は黒くなってしまいます。
結論
結論ですが、 Toolbar
に別で作成した Toolbar
用の スタイルを android:theme
に設定してあげます。
style.xml
...
<!-- Toolbar のタイトルを白くする -->
<style name="Toolbar.Light.Text" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:background">@color/colorPrimary</item>
</style>
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- style ではなく theme に設定します -->
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Toolbar.Light.Text"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ポイントは android:style
ではなく android:theme
に style.xml
に作成したスタイルを追加するところです。
android:style
に設定した場合は指定した View
(今回は ViewGroup
)にだけ作用します。
一方、 android:theme
に設定した場合は、特に ViewGroup
の場合は、その子ビューに対しても作用します。
これでテキストとアイコンは白くなります。
最後に
なんだかAndroidはアプリ内リソースを簡単に管理できるところは良いのですが、ちょっと複雑だなぁと改め思いました。
見ていただきありがとうございます。