Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a Toolbar theme in the App Theme in Android?

Currently I am using material components and material theme:

  <style name="BaseTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
   ...
   ...
   <item name="materialButtonStyle">@style/Button</item>
  </style>

I was able to define a style for every button using materialButtonStyle and I was wondering if it is possible to achieve the same for a toolbar.

THIS IS REALLY IMPORTANT: The idea is to avoid defining a style / theme in the appbar or toolbar component, but just use it a get the styles defined by the app theme.

I want to avoid this:

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:theme="@style/ToolbarTheme">

    <com.google.android.material.appbar.MaterialToolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:titleTextAppearance="@style/ToolbarTextAppearance"
      tools:title="Title" />

</com.google.android.material.appbar.AppBarLayout>

Inside the theme I want to be able to specify the font style and the text appearance.

These are my style:

  <style name="ToolbarTheme" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar">
  </style>

  <style name="ToolbarTextAppearance" parent="TextAppearance.AppCompat.Title">
    <item name="android:fontFamily">@font/nunito_bold</item>
  </style>

Using the code defined previously, I am able to get those changes. But as I mentioned, I want to defined that as part of my app theme like the material button.

I tried using this but I did not succeed:

<style name="BaseTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    ...
    <item name="appBarLayoutStyle">@style/ToolbarTheme</item>
    <item name="toolbarStyle">@style/ToolbarTheme</item>
</style>
like image 234
Leandro Ocampo Avatar asked Dec 17 '22 15:12

Leandro Ocampo


1 Answers

This code works for me just fine:

<resources>

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="appBarLayoutStyle">@style/AppTheme.AppBarOverlay</item>
        <item name="toolbarStyle">@style/AppTheme.Toolbar</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar">

        <item name="android:background">?colorPrimary</item>

    </style>

    <style name="AppTheme.Toolbar" parent="Widget.MaterialComponents.Toolbar">

        <item name="titleTextAppearance">@style/TextAppearance.MaterialComponents.Body1</item>

    </style>

</resources>
like image 120
Reza Bigdeli Avatar answered Dec 21 '22 10:12

Reza Bigdeli