2

Hi I have a shape drawable in xml and it is used as background of a view. Its color needs to be changed in the code depending on conditions.

So I am doing

  ShapeDrawable d =  (ShapeDrawable) getResources().getDrawable(R.drawable.shape1);

  d.getPaint().setShader(sd1);

but the getDrawable returns a gradient drawable, casting it to ShapeDrawable generates error.

So how can I get shapeDrawable in code and modify its attributes.

Sanjay Singh
  • 349
  • 5
  • 18
  • Set the `drawable` to an `ImageView` first. Following that, this would work - `(ShapeDrawable)imageView.getBackground();`. For more info, look at this answer: [Set android shape color programmatically](http://stackoverflow.com/a/17825210/2558882) – Vikram Aug 13 '13 at 15:28

4 Answers4

1

I was able to fix this by casting as a GradientDrawable instead of ShapeDrawable.

GradientDrawable shape = (GradientDrawable) getResources().getDrawable(R.drawable.shape1);

    shape.setColor(Color);

I used this when I created an activity with a custom style based on the Holo.Dialog theme.

1

This code snippet worked for me:

PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(getResources().getColor(R.color.your_color),PorterDuff.Mode.MULTIPLY);

imgView.getDrawable().setColorFilter(porterDuffColorFilter);
imgView.setBackgroundColor(Color.TRANSPARENT)
Mehatab
  • 1,689
  • 1
  • 11
  • 6
0

Here is how you can set the color:

d.getPaint().setColor(Color.BLACK);
Shaunak
  • 17,377
  • 5
  • 53
  • 84
0

I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.

This function returns a drawable.

public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
    Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate(); 
    mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN)); 
    return mDrawable;
} 

changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);
Pang
  • 9,564
  • 146
  • 81
  • 122
Sachin Tanpure
  • 1,068
  • 11
  • 12