0

我有一个文本视图,它获取名为 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 文件的所有其他属性并以编程方式更改梯度运行时。有人告诉我可以使用 StateListDrawable 和 GradientDrawable 来做到这一点。这是我不成功的尝试:

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

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

4

1 回答 1

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

于 2013-10-19T18:45:31.887 回答