2015-06-29 98 views
2

我有幾個不同的應用程序Activities。不同的活動有不同的風格按鈕,文本等......我已經設置了所有組件,以根據它們的位置/活動具有各種樣式。 (例如,style="@style/MainMenuActionBarTitlestyle="@style/MainMenuActionBarTagLine)。這些樣式設置backgroundDrawableMipMap,或Color),textColor,等...使用主題更改Android樣式

該應用程序將提供一些主題包,其在整個應用程序更改這些各種組件的顏色,我希望有Styles具有相同的名稱,但基於應用程序的Theme的值不同。這樣,只要Activity加載到用戶選擇的任何主題,我就可以更改Theme

關於如何更改標準小部件外觀&有一些很好的信息here感覺使用了主題,但是這改變了標準非風格小部件的外觀和感覺。

有沒有辦法使用主題完成此操作,還是完全是錯誤的方向?有更好/更容易的路線嗎?

編輯:在做了更多的研究和更多的搗鼓之後,我意識到我想做的事與我如何完成這一點並不遙遠。當我設置ActivityTheme時,我想要做的是實際更改組件Styles

回答

0

我發現的一個解決方案是使用attributes,其中Theme可以指向不同的Styles

attrs.xml

<resources> 
    <!-- Attributes referencing whatever style the theme needs to set up. --> 
    <attr name="main_menu_button_style_play" format="reference" /> 
</resources> 

的themes.xml

<resources> 
    <!-- Base application theme. --> 
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
     <!-- App specific attributes --> 
     <item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play</item> 
    </style> 

    <!-- Blue application theme. --> 
    <style name="AppTheme.Blue" parent="AppTheme"> 
     <!-- App specific attributes --> 
     <item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play.Blue</item> 
    </style> 
</resources> 

styles.xml

<style name="MainMenu.Button.Play"> 
    <item name="android:background">#f76d3c</item> 
    <item name="android:text">PLAY</item> 
</style> 

<style name="MainMenu.Button.Play.Blue"> 
    <item name="android:background">#2ca8c2</item> 
</style> 

activity.xml

<Button android:id="@+id/main_play_button" 
     style="?attr/main_menu_button_style_play"/> 

這種方法非常好,並允許我在Activity.onCreate()方法中設置Theme

唯一惱人的問題,我有這個解決方案是Android Studio中抱怨說,Button缺少layout_width,即使他們在Style正在定義layout_height。我想它不會通過選擇的Theme後面的屬性參考。

我最終使用的另一種方法是更多地使用屬性。爲所有屬性值創建屬性我想在主題之間進行更改。因此,我用main_menu_button_play_background來代替定義樣式參考的main_menu_button_style_play。這種方法的工作量與簡單指定樣式的工作量相同,因爲主題可以繼承,但IDE可以理解它。