Remarque : La réponse a été mise à jour pour couvrir le scénario oùbackground trouve une instance de ColorDrawable. Merci Tyler Pfaff , de l'avoir signalé.
Le dessinable est un ovale et est l'arrière-plan d'un ImageView
Obtenez le DrawabledeimageView utilisation getBackground():
Drawable background = imageView.getBackground();
Vérifiez contre les suspects habituels:
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));
}
Version compacte:
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));
}
Notez que la vérification des valeurs nulles n'est pas requise.
Cependant, vous devez utiliser mutate()sur les drawables avant de les modifier s'ils sont utilisés ailleurs. (Par défaut, les dessinables chargés à partir de XML partagent le même état.)