【问题标题】:android appcompat style for toolbar to match actionbar工具栏的 android appcompat 样式以匹配操作栏
【发布时间】:2015-08-26 03:37:48
【问题描述】:

我正在使用 android 支持库 ToolBar,并希望使用相同的背景颜色来匹配 ActionBar。

我查看了支持库源代码,找到了我要使用的 ActionBar 样式:

    <style name="Base.Widget.AppCompat.Light.ActionBar.Solid">
        <item name="background">?attr/colorPrimary</item>
        <item name="backgroundStacked">?attr/colorPrimary</item>
        <item name="backgroundSplit">?attr/colorPrimary</item>
    </style>

但是当我把它作为工具栏的样式放在我的布局中时,它就不起作用了:

    <android.support.v7.widget.Toolbar
        android:id="@+id/actiontoolbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        style="@style/Base.Widget.AppCompat.Light.ActionBar.Solid"
        />

但是,如果我只使用“android:background”而不是“style”,那么它可以工作:

    android:background="?attr/colorPrimary"

当我在工具栏布局中引用支持库样式时,有谁知道为什么它不起作用。我在 AndroidStudio 中使用 appcompat 22.2.0。 我也尝试了以下方法,但它们也不起作用:

    android:theme="@style/Base.Widget.AppCompat.Light.ActionBar.Solid"
    app:theme="@style/Base.Widget.AppCompat.Light.ActionBar.Solid"

【问题讨论】:

    标签: android android-actionbar styles toolbar


    【解决方案1】:

    这是因为工具栏需要一个主题。首先在 appcompat 父主题中定义您的颜色属性。

    <style name="MyTheme" parent="Theme.AppCompat"> 
        <item name="background">@color/colorPrimary</item>
        <item name="backgroundStacked">@color/colorPrimary</item>
        <item name="backgroundSplit">@color/colorPrimary</item>
    </style>
    

    只是为了确保使用颜色值。

    在工具栏中

    app:theme="@style/MyTheme"
    

    另外,请确保您有

    xmlns:app="http://schemas.android.com/apk/res-auto"
    

    IDE 可能会要求您自动更正此问题

    您的工具栏的最终外观将是

     <android.support.v7.widget.Toolbar
        android:id="@+id/actiontoolbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        app:theme="@style/MyTheme"
        />
    

    关于 Gabriele 的 更新:使用 appcompat 22.1.0,您可以使用

    android:theme
    

    【讨论】:

    • 使用 appcompat 22.1.0,您可以在工具栏中使用 android:theme
    • @Sheychan 我指的是一个主题是什么意思?主题和样式是相同的,唯一不同的是您如何将它们应用于应用程序、活动或视图。我已经尝试过这些组合,但它们仍然不起作用。 app:theme="@style/Base.Widget.AppCompat.Light.ActionBar.Solid" android:theme="@style/Base.Widget.AppCompat.Light.ActionBar.Solid" style="@style/Base.Widget. AppCompat.Light.ActionBar.Solid" 以上都不起作用。我正在使用带有 AndroidStudio 的 appcompat 22.2.0
    • @Sheychan 它不起作用。定义自己的主题或风格仍然行不通。我已经试过了。不知何故,这行 ​​... 从未被使用过。就像我在问题中提到的那样,如果有一个 android: 前缀作为独立或作为样式的一部分,它就可以工作。 ​​?attr/colorPrimary 有效。那么为什么使用“android:background”而不是“background”呢?我可以相信在较新的 API 上使用“android:background”,但在不存在 Toolbar 或 ActionBar 的 API 上,不应该使用“background”吗?
    • 我确实看到属性“背景”自 API 1 以来可用。这可能是为什么?有人确定这是否是应用属性的方式吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多