3 回答
TA贡献2016条经验 获得超9个赞
drawable是一个椭圆形,是ImageView的背景
Drawable从imageView使用中获取getBackground():
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()如果在其他地方使用它们,则应在修改之前使用drawables。(默认情况下,从XML加载的drawable共享相同的状态。)
TA贡献1817条经验 获得超6个赞
这样做:
ImageView imgIcon = findViewById(R.id.imgIcon); GradientDrawable backgroundGradient = (GradientDrawable)imgIcon.getBackground(); backgroundGradient.setColor(getResources().getColor(R.color.yellow));
TA贡献1815条经验 获得超13个赞
现在更简单的解决方案是使用您的形状作为背景,然后通过编程方式更改其颜色
view.getBackground().setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_OVER)
编辑:
就像评论中正确指出的人一样PorterDuff.Mode.SRC_ATOP
,如果您的背景有圆角等,您可能会想要使用。
- 3 回答
- 0 关注
- 475 浏览
添加回答
举报