更改colors.xml中设置的styles.xml中的颜色

时间:2019-03-10 06:41:18

标签: java android xml colors styles

我按照下面的方式在我的colors.xml中设置了自定义颜色,但是,可以按照下面的方式在我的styles.xml主题节点中更改/更新颜色;

colors.xml

<resources>
    <color name="themeBackground">#000000</color>
    <color name="darkColor">#000000</color>
    <color name="lightColor">#ffffff</color>
<resources>

并按照以下

中的说明在我的 v21 \ styles.xml 中进行手动更改
//used in activity
onCreate().setTheme(R.style.DarkTheme);

v21 \ styles.xml

<style name="DarkTheme">
    <!-- change themeBackground manually here -->
    <item name="themeBackground">@color/darkColor</item>
</style>

<style name="LightTheme">
    <!-- change themeBackground manually here -->
    <item name="themeBackground">@color/lightColor</item>
</style>

我已经尝试过了,但是没有运气,因为似乎只能更改android的值,即

<item name="colorPrimary">@color/lightColor</item>

1 个答案:

答案 0 :(得分:0)

有多种方法可以在运行时应用主题。其中一个已经很好地涵盖了here。这些方法的问题在于,您将必须通过调用recreate()来至少重新创建活动。但是您可能会遇到无法进行重新创建活动的情况,这可能是由于其对数据的依赖或现有架构模式的低效率所致。

在不重新创建活动的情况下,还有其他一些可行的方法:递归查找视图和应用主题。为了做到这一点,第一个约束是拥有所有自定义视图。

对于每个框架视图或视图组,请定义自定义视图,如下例所示:

class CustomTextView extends AppCompatTextView {}

现在,您将需要一个类似于以下示例的界面,该界面可以嵌入视图中并在动态更改主题时触发。

interface Painter {
  void applyTheme(int theme)
}

在您的自定义视图类中实现如下:

class CustomTextView extends AppCompatTextView implements Painter {
     @Override
     public void applyTheme(int theme) {
          switch (theme) { ... }
     }
}

在您的活动中的某处,递归地找到实现Painter并触发applyTheme的视图,如下所示:

public void onChangeThemeClick(int selectedTheme){
     View rootView = findViewById(android.R.id.content);
     paintRecurively(rootView,selectedTheme);
}

public void paintRecurively(View view, int theme) {
   //if view implements painter, trigger the method
   if(view instanceof Painter){
     (Painter)view.applyTheme(theme);
   }
   //if view is viewgroup then further call this method for its children.
   if(view instanceof ViewGroup){
      ViewGroup vg = (ViewGroup)view;
      for(...childCount of vg){
          paintRecurively(vg.getChildAt(i),theme);
      }
   }

}

这听起来像是很多工作。但是,仅当您不想重新创建活动时才需要做。