【问题标题】:Changing the color of a supportActionBar programmatically以编程方式更改 supportActionBar 的颜色
【发布时间】:2017-08-03 05:45:23
【问题描述】:

我遇到了一个问题,即更改支持 ActionBar 的背景可绘制对象会更改大部分栏的颜色,但会在文本和图标周围留下旧颜色。我尝试更改支持 ActionBar 和我用来制作它的 ToolBar 的颜色。我尝试了许多使 UI 元素无效的不同方法。我已经厌倦了设置颜色和文本是不同的顺序。我试过隐藏和显示文本。我就是不能让它变成一种纯色。

以下是我的 ActionBar 样式:

<style name="LocationBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@color/text_color_primary_inverse</item>
    <item name="android:textColorSecondary">@color/text_color_primary_inverse</item>
    <item name="android:background">@color/weather_cool</item>
</style>

这就是我将它添加到我的活动中的方式:

<android.support.v7.widget.Toolbar
    android:id="@+id/location_bar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:theme="@style/LocationBar"/>

这个在Java代码中我设置为supportActionBar:

_locationBar = (Toolbar)findViewById(R.id.location_bar);
setSupportActionBar(_locationBar);

然后在获取天气后,我尝试像这样调整颜色:

ColorDrawable warmDrawable = new ColorDrawable(ContextCompat.getColor(this, R.color.weather_warm));
getSupportActionBar().setBackgroundDrawable(warmDrawable);

这会导致您在图片中看到的内容。大部分栏会改变颜色,但不是全部。

【问题讨论】:

  • 你能分享你的styles.xml吗?
  • 改变主题可以在这里工作。
  • 我添加了更多信息。抱歉,来晚了,我没想到!

标签: android android-actionbar android-actionbar-compat


【解决方案1】:

...改变支持ActionBar的背景drawable改变了 大部分条的颜色,但在文本周围留下旧颜色和 图标...

发生这种情况的原因是您使用的是android:theme 而不是styletheme 应用到您的 Toolbar 中的每个孩子,在这种情况下包括 TextView 标题背景和您的设置按钮背景。 style 旨在用于视图级别,并且只会应用于您的 Toolbar 背景。

之前

<android.support.v7.widget.Toolbar
    ...
    android:theme="@style/LocationBar" />

之后

<android.support.v7.widget.Toolbar
    ...
    style="@style/LocationBar" />

【讨论】:

    【解决方案2】:

    在您的活动类中编写代码,如下所示。

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#004D40")));
    

    这会将背景颜色更改为 #004D40

    【讨论】:

    • 这就是我正在做的,并得到了图片中的结果。
    猜你喜欢
    • 2015-12-06
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多