【问题标题】:How to set several backgrounds in one theme如何在一个主题中设置多个背景
【发布时间】:2016-10-03 13:33:49
【问题描述】:

我完全卡住了(

UPD。是否可以通过应用单个主题为单独的 View 设置不同的背景(或其他属性)?

不同主题的不同视图应该如何应用不同的样式? 简而言之,我想根据一天中的时间更改主题,以相应地更改视图的属性(颜色、背景等)。

Profi,任何提示都会非常感激。

【问题讨论】:

  • 您目前面临的问题是什么?
  • 在我不知道该怎么做之前,这不是问题。是请求帮助。事情很复杂,我既不能提出正确的问题,也不能在网上找到能理解的东西。
  • 我想要的只是更改主题并使用另一个值设置视图的属性(-s)。
  • 检查this 更改主题和检查电话时间开始Service
  • 感谢您耐心地理解我的问题,但更改主题并不是我遇到的问题。看这里:TextView_1 有 Color.RED,TextView_2 有由 Theme_1 设置的 Color.GREEN。在实现方法 setTheme(Theme_2) 之后,我想将 TextViev_1 设置为 Color.GREEN 和 TextView_2 设置为 Color.RED 等等......而且更重要的是 - 怎么可能为两种不同的颜色定义两种不同的颜色一个主题中的 XML 样式资源中的 TextViews?我是否需要为每个视图创建具有不同名称的自定义“项目”?同志们,我现在完全迷失了……((

标签: android


【解决方案1】:

你应该像这样做 switch 语句:

        int theme;
        String color;

     switch (theme) {
                case 1:  color = redandblue;
    //code
                         break;
                case 2:  color = greenanddark;
    //code
                         break;
                case 3:  color = redandwhite;
    //code
                         break;

                default: color = standard;
    //default mean that this will be call when any upper not call 
                         break;

代码表示您对视图颜色的偏好

if else 你也可以这样做

if(theme == 1){
//code
}else if(theme == 2){
//code
}else if(theme == 3){
//code}
...

最后是用方法配置主题

private void configureFirstTheme(){
//code
}

private void configureSecondTheme(){
//code
}

你可以将构造函数添加到方法中

private void themeSetup(int theme){
//here the switch statement
}

希望你会选择一些东西

【讨论】:

  • 所以不可能仅仅通过应用另一个主题来改变视图的属性? “switchcasing”似乎是一个非常丑陋的机制来做到这一点。如果有两个以上的主题和大量自定义视图,则需要大量的手工编码((看起来很伤心
  • 可能。您还可以制作 if else 语句并为布局的每个配置制作方法。你有很多方法可以完成这项任务
  • 所以请给我从“许多”中正确执行此操作的确切方法。或提供指向资源的链接以供阅读。提前谢谢
  • 查看编辑答案。每种方式都是正确的。我更喜欢 switch 语句,但你更喜欢的是你的选择
  • 感谢罗德里克斯,感谢您的时间!
【解决方案2】:

我终于找到了一个合我心意的解决方案!我怀疑这些硬编码的方法不是很灵活的解决方案,需要复用代码取决于实现的主题数量。 对于面临相同任务的 thouse,请查看link

声明要用作样式参考的属性:

<declare-styleable name="CustomThemeViews">
<attr name="myViewStyle" format="reference"/>
</declare-styleable>     Define styles for each theme:

<style name="myViewStyleTheme01">
<item name="android:background">#f00</item>
</style>

<style name="myViewStyleTheme02">
<item name="android:background">#0f0</item>
</style>     Define themes that refer to different styles:

<style name="AppTheme" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme01</item>
</style>

<style name="AppThemeAlternative" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme02</item>
</style>     Use themed styles in layout

<ListView style="?attr/myViewStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"    
...     Now the style applied to the ListView changes according to the theme applied.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多