2012-12-19 84 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 /'**。那么它进展顺利。谢谢。 –