Android以编程方式更改可绘制的纯色
我有一个椭圆形的抽屉,里面有一个复选标记。 是否可以在不更改复选标记颜色的情况下以编程方式更改椭圆形颜色 这是我的绘图:Android以编程方式更改可绘制的纯色,android,colors,drawable,Android,Colors,Drawable,我有一个椭圆形的抽屉,里面有一个复选标记。 是否可以在不更改复选标记颜色的情况下以编程方式更改椭圆形颜色 这是我的绘图: <item> <shape android:shape="oval"> <solid android:color="@color/black" /> </shape> </item> <item> <bitmap android
<item>
<shape
android:shape="oval">
<solid android:color="@color/black" />
</shape>
</item>
<item>
<bitmap
android:src="@drawable/check_mark"/>
</item>
我想做的只是以编程方式将纯黑颜色更改为其他颜色只需添加另一个带有其他“椭圆形”颜色的可绘制图形,然后以编程方式替换可绘制图形就更容易了。您可以使用下面的参考代码以语法方式创建形状
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius(24);
shape.setShape(GradientDrawable.OVAL);
shape.setColor(R.color.red);
imageView.setBackground(shape);
可绘制的是椭圆形,是ImageView的背景 使用getBackground()从imageView中获取可绘制文件: 检查常见的嫌疑犯:
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));
}
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));
}