GradientDrawable created programmatically: setSize and setGradientCenter methods do not work

1.3k views Asked by At

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

1

There are 1 answers

0
moyo On

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