【问题标题】:How to set theme color in below api 21如何在下面的 api 21 中设置主题颜色
【发布时间】:2017-06-27 11:19:11
【问题描述】:

我有这个可绘制的 shape.xml,看起来没什么特别的:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <corners android:radius="4dp"/>
    <solid android:color="?colorPrimary"/>
</shape>

当我在 api 21 以下运行时它崩溃了,因为我认为它不支持使用
“?colorPrimary”。

用户可以正确选择不同的主题,那么我可以使用什么来代替下面 api 21 上的“?colorPrimary”?

如果我这样设置:

<solid android:color="@color/colorPrimary" />

然后我将为我的所有主题设置相同的颜色,这是不可取的。

在我的 styles.xml 中,我有 10 个不同的主题可供用户选择。

我知道我必须将 drawable shape.xml 移动到 drawable-v21 文件夹中,但是我应该如何更改默认 drawable 文件夹中相同的 shape.xml 以提供相同的功能?

【问题讨论】:

  • 你为什么不试试这个——android:textColor="@color/colorPrimary"
  • 此 shape.xml 用作 ListView 项的背景。在我的蓝色主题中,背景是蓝色的,在我的红色主题中,B 被读取
  • 我最终从接受的答案 here 中做了类似 this 的操作

标签: android colors themes


【解决方案1】:

我们还有另一个选择 而不是在编译时在 drawable 中创建 shape.xml 在运行时使用 java 创建它

在运行时获取主题颜色并在运行时创建形状时使用它

GradientDrawable gradientDrawable=new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setColor(getResources().getColor(R.color.colorAccent));
gradientDrawable.setSize(200,200);
gradientDrawable.setCornerRadius(100);

或者你可以从 xml 中膨胀现有的形状并像这样改变它的属性,

GradientDrawable shapeDrawable= (GradientDrawable) 
ContextCompat.getDrawable(this,R.drawable.shape);
shapeDrawable.setColor(getResources().getColor(R.color.colorPrimary));
imageView.setImageDrawable(shapeDrawable);

【讨论】:

    【解决方案2】:

    我认为您应该尝试在 res 文件夹中创建不同的值文件夹,例如

    价值观-v19 values-v21 等

    而且您还检查了您的 java 类中的一件事以防止强制关闭

    // 检查我们是否在 Android 5.0 或更高版本上运行

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Call some material design APIs here
    } else {
        // Implement this feature without material design
    }
    

    【讨论】:

    • 不同的值文件夹如何设置我的 shape.xml 颜色。感觉我必须为每个主题创建 10 个 shape.xml 文件不知道
    【解决方案3】:

    你必须为不同的颜色主题编写不同的drawable

    【讨论】:

    • 为每个主题创建 10 个可绘制 shape.xml 文件?
    • api bellow 21 不支持 shape.xml 中的任何颜色属性
    • 如果你想支持21以上的api你可以在shape.xml中使用color属性
    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2021-11-29
    • 2013-06-07
    相关资源
    最近更新 更多