使用 AppCompat 在 pre-lollipop 上的 drawable 中使用 colorPrimary

Use colorPrimary in drawable on pre-lollipop with AppCompat

我正在使用 AppCompat 22.1.1。

由于某些原因,我的应用程序可以在用户导航期间动态更改其主题。 (例如,当您从 "my apps" 部分移动到 "movie" 部分时,移动到应用程序的另一部分,例如 google Play 商店应用程序)

为了避免为每个主题创建一个可绘制背景,我尝试创建这样的背景:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="?attr/colorPrimary" /></shape>

当以编程方式更改主题时,我想 colorPrimary 也会更改,之后膨胀的按钮将染上新主题的颜色。

但是我在棒棒糖之前有一个膨胀异常(但在棒棒糖上有效)。 drawable找不到属性attr/colorPrimary,为什么?

这是我正在使用的简单 theme.xml:

 <style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/my_blue</item>
    <item name="colorPrimaryDark">@color/my_blue_dark</item>
    <item name="colorAccent">@color/my_blue_light</item>
</style>

颜色在 values/colors.xml 中,只有六色。所有资源都在 "values" 目录中,而不是在 values-r21 目录中。

根据我的经验,我不知道,但我很确定你无法通过 XML 做任何事情。大量的框架资源以some_drawable_dark.xmlsome_drawable_light.xml的形式提供了两次;您似乎无法从 drawablecolor 文件夹中引用主题值。

所以你应该:

  • 创建x个静态资源,其中x是你放入的主题数量;
  • 运行时运行,使用setColorFilter()等。视情况而定,这可能很难。

在res/color/:

中创建一个color_primary.xml颜色资源
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="?attr/colorPrimary"/>
</selector>

然后在您的可绘制对象中引用它:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
   <solid android:color="@color/color_primary" />
</shape>