如何在 Android 的 App Theme 中指定 Toolbar 主题?

Lea*_*mpo 3 android android-theme android-toolbar material-components material-components-android

目前我正在使用材料组件和材料主题:

  <style name="BaseTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
   ...
   ...
   <item name="materialButtonStyle">@style/Button</item>
  </style>
Run Code Online (Sandbox Code Playgroud)

我能够使用 materialButtonStyle 为每个按钮定义样式,我想知道是否可以为工具栏实现相同的样式。

这真的很重要:这个想法是为了避免在应用程序栏或工具栏组件中定义样式/主题,而只是使用它来获取应用程序主题定义的样式。

我想避免这种情况:

<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>
Run Code Online (Sandbox Code Playgroud)

在主题中,我希望能够指定字体样式和文本外观。

这些是我的风格:

  <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>
Run Code Online (Sandbox Code Playgroud)

使用之前定义的代码,我能够获得这些更改。但正如我所提到的,我想将其定义为我的应用程序主题的一部分,例如材质按钮。

我尝试使用它,但没有成功:

<style name="BaseTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    ...
    <item name="appBarLayoutStyle">@style/ToolbarTheme</item>
    <item name="toolbarStyle">@style/ToolbarTheme</item>
</style>
Run Code Online (Sandbox Code Playgroud)

Rez*_*eli 8

这段代码对我来说很好用:

<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>
Run Code Online (Sandbox Code Playgroud)