如何通过编程更改AppCompat v21工具栏主题?

26

这是我的工具栏 XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    app:contentInsetEnd="0dp"
    app:contentInsetStart="0dp"
    android:layout_height="@dimen/toolbar_height"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:background="@color/primary_color">



</android.support.v7.widget.Toolbar>

我想通过编程方式更改 app:theme,请问应该如何操作?


您不能更改样式和主题。您想做什么?也许有另一种解决方案。 - krystian71115
我想让用户选择工具栏的颜色... 根据所选颜色,我想改变主题.. 所以如果他们选择了深色主题,主题将是ThemeOverlay.AppCompat.Dark.ActionBar,否则它将是浅色主题。 - Shehan Ekanayake
并附上如何设置图块颜色的答案链接:https://dev59.com/jWkw5IYBdhLWcg3wZJt-#26594674 - krystian71115
2个回答

25

使用以下代码片段添加主题:

Toolbar toolbar;
toolbar.getContext().setTheme(R.style.ThemeOverlay_AppCompat_Dark_ActionBar);

1
对我有用..谢谢 - Mr Code
是的!这个方法可行!其他答案都过于复杂,而且有些并不起作用。我试过的那些也没用。谢谢你。 - Peter Griffin
2
对我来说,这做得比我想要的多。它设置了我的整个活动的主题,而不仅仅是工具栏。如果您的活动中有其他响应主题的元素,请小心。 - lostintranslation
4
有危险,可能会破坏你活动的主题。 - Suhaib Roomy
对我来说(对于API 30),它没有起作用。它肯定会将主题应用于工具栏的上下文,这显然是您的活动。 - Tayyab Amin
如果这是一个自定义工具栏实现,我该如何做?我想有条件地切换样式。 - Skj

25
您可以通过编程或样式来完成此操作:
Toolbar toolbar; // your toolbar
toolbar.setBackgroundColor(newColor); // i don't tested this method. Write if it's not working
toolbar.setTitleTextColor(titleColor); // if toolbar is white set title to black, if toolbar is black set title to white

或者您可以使用样式来完成:

添加 attrs.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="toolbarStyle" format="reference"/>
</resources>

现在更改toolbar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    app:contentInsetEnd="0dp"
    app:contentInsetStart="0dp"
    android:layout_height="@dimen/toolbar_height"
    app:theme="?attr/toolbarStyle"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:background="@color/primary_color">



</android.support.v7.widget.Toolbar>

在styles.xml中(如果没有,则创建它):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyStyle.Dark" parent="AppCompat.Theme">
        <item name="toolbarStyle">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
    </style>
    <style name="MyStyle.Light" parent="AppCompat.Theme.Light">
        <item name="toolbarStyle">@style/ThemeOverlay.AppCompat.Light.ActionBar</item>
    </style>
</resources>

如果您选择第二种方法(使用样式),您必须在super.onCreate()之前重新启动活动并使用setTheme方法。
希望我对您有所帮助。

1
嗨,Krystian。第一种方法不起作用。但也许你知道如何在一个Activity实例内替换片段之间更改工具栏的方法?需要避免Activity重新创建。谢谢。 - Taras Vovkovych

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接