2015-07-04 98 views
11

這是我的工具欄XML如何以編程方式更改AppCompat v21工具欄主題?

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

我想改變應用:主題編程。 我該怎麼做?

+0

你不能改變的風格和主題。您想做什麼?也許有一個不同的解決方案。 – krystian71115

+0

那麼我想讓用戶選擇顏色的工具欄....根據我想改變主題的顏色..所以,如果他們選擇一個深色的主題將是ThemeOverlay.AppCompat.Dark.ActionBar,否則它會是輕的主題 –

+0

和鏈接回答如何設置瓷磚顏色:http://stackoverflow.com/a/26594674/2536878 – krystian71115

回答

18

爲此,您可以編程方式或風格:

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()方法

我希望我幫你。

+0

嗨,克里斯蒂安。第一種方法不起作用。但也許你現在的方式如何更換片段之間的替代一個Activity實例內的工具欄?需要避免活動重新創建。謝謝 –

6

使用下面的代碼片段添加一個主題:

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

爲我工作..謝謝 –

相關問題