动态设置主题颜色

Tom*_*m11 9 android themes colors android-activity

我在我的Android应用程序中使用主题(动态),如下所示:

my_layout.xml(提取):

<TextView
    android:id="@+id/myItem"
    style="?my_item_style" />
Run Code Online (Sandbox Code Playgroud)

attrs.xml(提取):

<attr name="my_item_style" format="reference" />
Run Code Online (Sandbox Code Playgroud)

themes.xml(提取):

<style name="MainTheme.Blue">
      <item name="my_item_style">@style/my_item_style_blue</item>
</style>

<style name="MainTheme.Green">
      <item name="my_item_style">@style/my_item_style_green<item>
</style>
Run Code Online (Sandbox Code Playgroud)

styles.xml(提取):

<style name="my_item_style_blue">
      <item name="android:textColor">@color/my_blue</item>
</style>

<style name="my_item_style_green">
      <item name="android:textColor">@color/my_blue</item>
</style>
Run Code Online (Sandbox Code Playgroud)

所以,正如你所看到的,我正在动态设置主题.我正在使用这堂课:

public class ThemeUtils {

  private static int sTheme;
  public final static int THEME_BLUE = 1;
  public final static int THEME_GREEN = 2;

  public static void changeToTheme(MainActivity activity, int theme) {
      sTheme = theme;
      activity.startActivity(new Intent(activity, MyActivity.class));
  }

  public static void onActivityCreateSetTheme(Activity activity)
  {
      switch (sTheme)
      {
          default:
          case THEME_DEFAULT:
          case THEME_BLUE:
              activity.setTheme(R.style.MainTheme_Blue);
              break;
          case THEME_GREEN:
              activity.setTheme(R.style.MainTheme_Green);
              break;
      }
  }
Run Code Online (Sandbox Code Playgroud)

}

我想知道的是,有没有办法在代码中如何做到这一点(更改主题颜色)?例如,我有以下代码(提取):

((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);
Run Code Online (Sandbox Code Playgroud)

它可以通过一些辅助方法来完成,该方法将使用switch可用主题的命令并返回主题的正确颜色.但我想知道是否有更好,更好,更快的方式.

谢谢!

Tom*_*m11 5

我终于使用以下方法完成了它:

public static int getColor(String colorName) {
    Context ctx = getContext();
    switch (sTheme) {
        default:
        case THEME_DEFAULT:
            return ctx.getResources().getIdentifier("BLUE_" + colorName, "color", ctx.getPackageName());
        case THEME_BLUE:
            return ctx.getResources().getIdentifier("BLUE_" + colorName, "color", ctx.getPackageName());
        case THEME_GREEN:
            return ctx.getResources().getIdentifier("GREEN_" + colorName, "color", ctx.getPackageName());
    }
}
Run Code Online (Sandbox Code Playgroud)

这会根据我的主题返回颜色(我使用了前缀)。