Reputation: 349
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.
Upvotes: 2
Views: 2392
Reputation: 1769
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)
Upvotes: 1
Reputation: 1146
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);
Upvotes: 0
Reputation: 168
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.
Upvotes: 1
Reputation: 18026
Here is how you can set the color:
d.getPaint().setColor(Color.BLACK);
Upvotes: 0