1

I'm trying to set a gradient to my toolbar but it seems like setSize and setGradientCenter do not work.

I need to create it dynamically because the center and height of the gradient vary depending on the values I get from a CMS, but I am unable to make this work. No matter what values I set for size and center, the gradient always gets the size of the entire toolbar and the center is the default one.

I tried calling mutate() first as the documentation says, with no result. Also tried setBounds with the same result

GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setOrientation(gradientData.getOrientation());
        gradientDrawable.setColors(gradientData.getColors());
        gradientDrawable.setGradientCenter(gradientData.getCenterX(), gradientData.getCenterY());

toolbar.setBackground(gradientDrawable);

Am I missing something? Orientation is always Linear if that matters

moyo
  • 1,312
  • 1
  • 13
  • 29
  • use `ClipDrawable` if all you want is to clip another Drawable making it wider / shorter depending on current level – pskink Feb 16 '17 at 10:54
  • @pskink I don't want to clip it, because I wouldn't have the entire gradient if I do it. For example if I have an end color, I wouldn't even see it if I clip it. I just want the gradient to be shorter, or modify the center so that the gradient effect ends sooner – moyo Feb 16 '17 at 11:00
  • so use `ScaleDrawable`: *A Drawable that changes the size of another Drawable based on its current level value* – pskink Feb 16 '17 at 11:01
  • or you could use `ShapeDrawable` and setup its `ShapeDrawable.ShaderFactory` so that you can use any `android.graphics.Shader` you want – pskink Feb 16 '17 at 11:31
  • @pskink any examples? – moyo Feb 16 '17 at 11:35
  • examples of what? ScaleDrawable? – pskink Feb 16 '17 at 11:35
  • ShapeDrawable. I tried ScaleDrawable and same result, there's no way to modify the height – moyo Feb 16 '17 at 11:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135852/discussion-between-moyo-and-pskink). – moyo Feb 16 '17 at 11:54

1 Answers1

3

I'll leave here the code in case it's useful for anybody else.

Thanks to @pskink example, it works using a ScaleDrawable. Now I can set a smaller gradient to my toolbar:

int[] colors = {
        Color.RED, Color.YELLOW, Color.RED
};

Drawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
final Drawable sd = new ScaleDrawable(gd, Gravity.TOP, 0, 1);
sd.setLevel(7500);

toolbar.setBackground(sd);
moyo
  • 1,312
  • 1
  • 13
  • 29