是否可以从 styles.xml 文件中引用属性?

Is it possible to reference attributes from styles.xml file?

我想让用户可以切换整个应用程序的颜色皮肤。我的意思是当用户按下屏幕按钮时动态切换应用程序的某些自定义视图的样式。我知道,如果您在 onCreate() 方法之前调用 Activity.setTheme(),您可以动态更改应用程序的主题,但普通视图(例如,NavigationView)在其 xml 布局,没有 setTheme 或 setStyle 方法,因此似乎无法动态更改它们的样式。

我认为我的 objective 可能会引用在 styles.xml 文件中声明的 AppTheme 中声明的颜色。我的意思是,我可以声明两个 AppTheme,每个都有一组颜色,然后在为自定义视图声明的自定义样式中引用这些颜色。像这样:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="customColor">#111111</item>
    </style>

    <style name="AppTheme.AnotherColor" parent="Theme.AppCompat">
        <item name="customColor">#222222</item>
    </style>

    <style name="CustomActionBar">
        <!-- title text color -->
        <item name="android:textColorPrimary">@styles/customColor</item>
    </style>
</resources>

因此,默认情况下,我的 "AppTheme" 上声明的自定义颜色将默认应用,使用颜色 111111。但是当我使用 setTheme(R.styles.AppTheme_AnotherColor) 更改我的应用程序的主题时,应用的颜色将是 222222。如果这将是可能的,那将是完美的!但这是不可能的,或者我不知道如何直接从同一 styles.xml 文件的另一种样式访问样式内声明的颜色。我的意思是 @styles/customColor 不正确,我不知道如何访问该颜色。

如何实现?

是的,绝对可以向主题添加自定义属性和颜色。为此,您需要:

  1. res/values/attrs.xml 文件中定义自定义属性:

    <resources>
        <attr name="customColor" format="color" />
    </resources>
    
  2. 在您的主题中定义属性值:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="customColor">#111111</item>
    </style>
    
    <style name="AppTheme.AnotherColor" parent="Theme.AppCompat">
        <item name="customColor">#222222</item>
    </style>
    
  3. 在样式中使用自定义属性:

    <style name="CustomActionBar">
        <!-- title text color -->
        <item name="android:textColorPrimary">?attr/customColor</item>
    </style>