更改XML的渐变

时间:2013-10-19 16:58:29

标签: android xml

我有一个textview,它将名为background.xml的文件作为其背景。这是background.xml的代码

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<shape android:padding="50dp"
android:shape="rectangle">
<gradient android:startColor="@color/sendDarkColorGreen"   android:centerColor="@color/sendDarkColorGreen" android:endColor="@color/sendLightColorGreen" android:angle="90"/>

                   

我正在尝试保留此xml文件的所有其他属性,并以编程方式更改gradiento n运行时。我被告知我可以使用StateListDrawable和GradientDrawable来执行此操作。这是我失败的attemot:

TextView myTextView1 = ......
StateListDrawable sld = new StateListDrawable();
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(myColor);
sld.addState(new int[] { android.R.attr.state_enabled }, drawable);
myTextView1.setBackgroundDrawable(sld);

但这似乎没有做任何事情。我这样做了吗?

1 个答案:

答案 0 :(得分:0)

您不必使用StateListDrawable以编程方式更改渐变。您可以改为使用这样的自定义函数设置渐变:

// Set background color         
    FillCustomGradient(findViewById(R.id.myTextView1), true,
            R.color.sendDarkColorGreen, R.color.sendDarkColorGreen, 
            R.color.sendLightColorGreen, R.color.sendLightColorGreen); 

// Set custom gradient
private void FillCustomGradient(View v, boolean roundCorners, final int color1, final int color2, final int color3, final int color4) {
    final View view = v;
    Drawable[] layers = new Drawable[1];

    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(
                    0,
                    0,
                    0,
                    view.getHeight(),
                    new int[] {
                             getResources().getColor(color1), 
                             getResources().getColor(color2),
                             getResources().getColor(color3),
                             getResources().getColor(color4)},
                    new float[] { 0, 0.49f, 0.50f, 1 },
                    Shader.TileMode.CLAMP);
            return lg;
        }
    };
    PaintDrawable p = new PaintDrawable();
    p.setShape(new RectShape());
    p.setShaderFactory(sf);
    if (roundCorners) {
        p.setCornerRadii(new float[] { 15, 15, 15, 15, 15, 15, 15, 15 });
    } else {
        p.setCornerRadii(new float[] { 0, 0, 0, 0, 0, 0, 0, 0 });           
    }
    layers[0] = (Drawable) p;

    LayerDrawable composite = new LayerDrawable(layers);
    view.setBackgroundDrawable(composite);
}

您可以通过传递LinearGradient中x0,y0,x1,y1参数的参数来更新代码以设置渐变线角度,请参阅:LinearGradient Docs