以编程方式更改supportActionBar的颜色

时间:2017-08-02 06:25:55

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

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

Should be all orange

这就是我的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);

这会导致您在图片中看到的内容。大多数酒吧都会改变颜色但不是全部。

2 个答案:

答案 0 :(得分: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" />

答案 1 :(得分:0)

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

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

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

相关问题