【问题标题】:Android change drawable solid color programmaticallyAndroid以编程方式更改可绘制纯色
【发布时间】:2025-12-29 04:50:07
【问题描述】:
我有一个椭圆形的drawable,里面有一个复选标记。
是否可以在不更改复选标记颜色的情况下以编程方式更改椭圆颜色?
这是我的可绘制对象:
<item>
<shape
android:shape="oval">
<solid android:color="@color/black" />
</shape>
</item>
<item>
<bitmap
android:src="@drawable/check_mark"/>
</item>
我想做的只是以编程方式将纯黑色更改为其他颜色
【问题讨论】:
标签:
android
colors
drawable
【解决方案1】:
用其他“椭圆”颜色添加第二个可绘制对象然后以编程方式替换可绘制对象会更容易。
【解决方案2】:
您可以使用以下参考代码从语法上创建形状。
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(24);
shape.setShape(GradientDrawable.OVAL);
shape.setColor(R.color.red);
imageView.setBackground(shape);
【解决方案3】:
drawable 是一个椭圆,是 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));
}