2012-12-19 82 views
4

我有一個簡單的問題。我想爲我的用戶界面提供多個主題,用戶可以在允許樣式爲主題

之間切換

問題是我可以使用樣式原始UI類的主題,或者我可以直接在XML佈局元素上使用樣式,但我無法定義將根據我應用的主題更改的樣式。不是我想要做的所有樣式都是基於原始類型。

我想說,我想要做的就像使用CSS選擇器來設置類或ID的樣式,但主題只允許您設置元素名稱的樣式。


我現在能做的最好是有一個從任何繼承的實際風格我已經建立,如下一個基本樣式:

我RES /價值/ style.xml

在我layout.xml
// All styles have to be subclassed here to be made generic, and only one 
// can be displayed at a time. Essentially, I'm doing the same thing as setting 
// a theme does, but for styles. If I have 50 styles, I have to have 50 of 
// these for each theme, and that's not DRY at all! 
<style name="MyHeaderStyle" parent="MyHeaderStyle.Default"/> 
<!-- 
    <style name="MyHeaderStyle" parent="MyHeaderStyle.Textures"/> 
--> 

<style name="MyHeaderStyle.Default"> 
    <item name="android:background">@android:color/background_dark</item> 
</style> 

<style name="MyHeaderStyle.Textures"> 
    <item name="android:background">@drawable/header_texture</item> 
</style> 

用法:

<!-- Note that I can't use a theme here, because I only want to style a 
    SPECIFIC element --> 
<LinearLayout android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       style="@style/MyHeaderStyle" 
       android:gravity="center"> 
</LinearLayout> 

回答

5

試試這個方法:

1)定義你自己的res/values/attrs.xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <declare-styleable name="AppTheme"> 
     <attr name="myLinearLayoutStyle" format="reference" /> 
    </declare-styleable> 

</resources> 

2)指定上述ATTR到你的LinearLayout

<LinearLayout android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       style="?attr/myLinearLayoutStyle" 
       android:gravity="center"> 
</LinearLayout> 

3)指定一個具體的風格,這ATTR:

<style name="AppLightTheme" parent="android:Theme.Holo.Light"> 
    <item name="@attr/myLinearLayoutStyle">@style/lightBackground</item> 
</style> 

<style name="AppTheme" parent="android:Theme.Holo"> 
    <item name="@attr/myLinearLayoutStyle">@style/darkBackground</item> 
</style> 

<style name="lightBackground"> 
    <item name="android:background">#D1CBF5</item> 
</style> 

<style name="darkBackground"> 
    <item name="android:background">#351BE0</item> 
</style> 

希望我能正確理解你的問題。

+0

我還沒有機會嘗試這個,但這個解決方案看起來很有前途。謝謝。 –

+0

我已經使用你的代碼。但它有一個問題。您必須從樣式定義中移除**'@ attr /'**。那麼它進展順利。謝謝。 –