以编程方式设置android形状颜色

以编程方式设置android形状颜色

问题描述:

我正在编辑以使问题更简单,希望这有助于获得准确的答案.

I am editing to make the question simpler, hoping that helps towards an accurate answer.

假设我有以下 oval 形状:

Say I have the following oval shape:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:angle="270"
           android:color="#FFFF0000"/>
    <stroke android:width="3dp"
            android:color="#FFAA0055"/>
</shape>

如何在活动类中以编程方式设置颜色?

How do I set the color programmatically, from within an activity class?

注意:已更新答案以涵盖 backgroundColorDrawable.感谢 Tyler Pfaff 指出这一点.

Note: Answer has been updated to cover the scenario where background is an instance of ColorDrawable. Thanks Tyler Pfaff, for pointing this out.

drawable 是一个椭圆形,是一个 ImageView 的背景

The drawable is an oval and is the background of an ImageView

使用getBackground()imageView获取Drawable:

Drawable background = imageView.getBackground();

检查常见的嫌疑人:

if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    // cast to 'GradientDrawable'
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    // alpha value may need to be set again after this call
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

精简版:

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

请注意,不需要进行空检查.

Note that null-checking is not required.

但是,如果在其他地方使用它们,您应该在修改它们之前在可绘制对象上使用 mutate().(默认情况下,从 XML 加载的 drawable 共享相同的状态.)

However, you should use mutate() on the drawables before modifying them if they are used elsewhere. (By default, drawables loaded from XML share the same state.)