5

I have the following gradient

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:angle="90"
    android:centerColor="#42f448"
    android:centerX="0.5"
    android:centerY="0.5"
    android:endColor="#000000"
    android:startColor="#000000"
    android:type="linear" />

What I need to do is change the center of the gradient based on position change on a ListView. Is it possible to create this gradient programmatically?

I've tried this approach, but if I change the center values, nothing happens, it remains fixed:

int colors[] = {0xff000000, 0xff42f448, 0xff000000};
    GradientDrawable shape = new GradientDrawable();
    shape.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM);
    shape.setColors(colors);
    shape.setGradientCenter(0.3f, 0.3f);
    view.setBackgroundDrawable(shape);

What am I missing? Thank you.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Phantom
  • 968
  • 3
  • 14
  • 32
  • 1
    You can't. Looks there is an open issue. Check this answer: https://stackoverflow.com/a/14383974/334522 – sromku Oct 11 '17 at 08:06
  • @sromku I saw this post, but it's 4 years old, I thought maybe it was resolved – Phantom Oct 11 '17 at 08:16
  • Unfortunately it wasn't, as it looks from last comments from 2017 - https://issuetracker.google.com/issues/36944181 :( – sromku Oct 11 '17 at 08:56

1 Answers1

4

You can achieve your goal by using Shader

ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        return new LinearGradient(width/2, 0, width/2, height,
                new int[]{0xff000000, 0xff42f448, 0xff000000},
                new float[]{0, 0.3f, 1},  // start, center and end position
                Shader.TileMode.CLAMP);
    }
};

PaintDrawable pd = new PaintDrawable();
pd.setShape(new RectShape());
pd.setShaderFactory(sf);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackground(pd);
} else
    layout.setBackgroundDrawable(pd);
SiSa
  • 2,594
  • 1
  • 15
  • 33
  • I've tried your solution, but the result is the same. The .setGradientCenter does nothing when I apply the colors like that. – Phantom Oct 11 '17 at 08:18