Set android shape color programmatically Set android shape color programmatically android android

Set android shape color programmatically


Note: Answer has been updated to cover the scenario where background is an instance of ColorDrawable. Thanks Tyler Pfaff, for pointing this out.

The drawable is an oval and is the background of an ImageView

Get the Drawable from imageView using getBackground():

Drawable background = imageView.getBackground();

Check against usual suspects:

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));}

Compact 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));}

Note that null-checking is not required.

However, you should use mutate() on the drawables before modifying them if they are used elsewhere. (By default, drawables loaded from XML share the same state.)


A simpler solution nowadays would be to use your shape as a background and then programmatically change its color via:

view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)

See PorterDuff.Mode for the available options.

UPDATE (API 29):

The above method is deprecated since API 29 and replaced by the following:

view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)

See BlendMode for the available options.


Do like this:

    ImageView imgIcon = findViewById(R.id.imgIcon);    GradientDrawable backgroundGradient = (GradientDrawable)imgIcon.getBackground();    backgroundGradient.setColor(getResources().getColor(R.color.yellow));