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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With