Hinweis : Die Antwort wurde aktualisiert, um das Szenario abzudecken, in dem backgroundsich eine Instanz von befindet ColorDrawable. Vielen Dank an Tyler Pfaff für diesen Hinweis.
Das Zeichenobjekt ist oval und bildet den Hintergrund einer ImageView
Holen Sie sich das Drawableaus imageViewmit getBackground():
Drawable background = imageView.getBackground();
Überprüfen Sie gegen übliche Verdächtige:
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));
}
Kompakte Version:
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));
}
Beachten Sie, dass keine Nullprüfung erforderlich ist.
Sie sollten mutate()die Drawables jedoch verwenden, bevor Sie sie ändern, wenn sie an anderer Stelle verwendet werden. (Standardmäßig haben aus XML geladene Drawables denselben Status.)