如何以编程方式更改AppCompat v21工具栏主题? [英] How to change AppCompat v21 toolbar theme programmatically?

查看:81
本文介绍了如何以编程方式更改AppCompat v21工具栏主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的工具栏xml

This is my 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="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:background="@color/primary_color">



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

我想以编程方式更改 app:theme . 我该怎么做?

I want to change app:theme programmatically. How do i do this?

推荐答案

您可以通过编程或以下方式进行此操作:

You can do this programmatically or with style:

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:

Add attrs.xml:

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

现在更改toolbar.xml:

And now change 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中(如果没有创建此文件):

And in styles.xml (if you don't have this create it):

<?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方法

If you select second method (with styles) you must restart activity and use setTheme method before super.onCreate()

希望我能对您有所帮助.

I hope I helped you.

这篇关于如何以编程方式更改AppCompat v21工具栏主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆