我正在编辑以使问题更简单,希望这有助于获得准确的答案。
假设我有以下 oval
形状:
<?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>
如何在 Activity 类中以编程方式设置颜色?
最佳答案
注意:答案已更新以涵盖 background
是 ColorDrawable
实例的情况>。谢谢 Tyler Pfaff , 指出这一点。
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));
}
请注意,不需要检查空值。
但是,如果在其他地方使用它们,您应该在修改它们之前在可绘制对象上使用 mutate()
。 (默认情况下,从 XML 加载的可绘制对象共享相同的状态。)
关于android - 以编程方式设置 android 形状颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17823451/