2017-10-11 75 views
2

我有以下梯度更改漸變中心動態

<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" /> 

我需要做的是改變基於一個ListView位置變化的漸變中心。是否有可能以編程方式創建此漸變?

我試過這種方法,但如果我改變中心值,沒有任何反應,它保持不變:

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

我缺少什麼?謝謝。

+1

你不能達到你的目標。看起來有一個公開的問題。檢查這個答案:https://stackoverflow.com/a/14383974/334522 – sromku

+0

@sromku我看到這個帖子,但它是4歲,我想也許它已經解決了 – Phantom

+0

不幸的是,它不是,因爲它從最後的評論從2017年起 - https://issuetracker.google.com/issues/36944181 :( – sromku

回答

1

您可以通過使用着色器

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

我試過你的解決方案,但結果是一樣的,當我應用這種顏色時.setGradientCenter不做任何事情。 – Phantom

+0

@Phantom I編輯我的代碼 – SiSa

+0

謝謝,這個解決方案有效。 – Phantom