简体   繁体   English

Android 以编程方式更改可绘制纯色

[英]Android change drawable solid color programmatically

I have a drawable that is an oval shape with a with check mark inside.我有一个椭圆形的drawable,里面有一个复选标记。 Is it possible to change the oval color programmatically without changing the check mark color?是否可以在不更改复选标记颜色的情况下以编程方式更改椭圆颜色?

Here's my drawable:这是我的可绘制对象:

<item>
    <shape
        android:shape="oval">
        <solid android:color="@color/black" />
    </shape>
</item>
<item>
    <bitmap
        android:src="@drawable/check_mark"/>
</item>

What I would like to do is only change the solid black color to something else programmatically我想做的只是以编程方式将纯黑色更改为其他颜色

It would be easier to just add a second drawables with other "oval"-color and then replace the drawable programmatically.使用其他“椭圆”颜色添加第二个可绘制对象然后以编程方式替换可绘制对象会更容易。

You can grammatically create a shape using below reference code.您可以使用以下参考代码以语法方式创建形状。

GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(24);
shape.setShape(GradientDrawable.OVAL);
shape.setColor(R.color.red);
imageView.setBackground(shape);

The drawable is an oval and is the background of an ImageView可绘制对象是椭圆形,是 ImageView 的背景

Get the Drawable from imageView using getBackground():使用 getBackground() 从 imageView 获取 Drawable:

Drawable background = imageView.getBackground();

Check against usual suspects:检查通常的嫌疑人:

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));
}

Compact version:紧凑型:

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM