我要实现的目标是在其中使用带有两个图层的Drawable,但在运行时控制一些值,例如渐变的startColor。这是my_layered_shape.xml中的内容:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item>
    <shape android:shape="rectangle">
      <stroke android:width="1dp" android:color="#FF000000" />
      <solid android:color="#FFFFFFFF" />
    </shape>
  </item>
  <item android:top="1dp" android:bottom="1dp">
    <shape android:shape="rectangle">
    <stroke android:width="1dp" android:color="#FF000000" />
    <gradient
      android:startColor="#FFFFFFFF"
      android:centerColor="#FFFFFF88"
      android:endColor="#FFFFFFFF"
      android:gradientRadius="250"
      android:centerX="1"
      android:centerY="0"
      android:angle="315"
    />
    </shape>
  </item>
</layer-list>

而且,如果我使用mMyImageView.setBackgroundResource(R.drawable.my_layered_shape),它就可以工作。
如果有必要,我不介意分割xml,或者只要有办法获取各种颜色值,就可以通过编程方式完成整个操作。我将以编程方式使用的概念(即,我在执行与此XML相同的代码时的最佳表现)是:
Drawable[] layers = new Drawable[2];

ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
sd1.getPaint().setColor(0xFFFFFFFF);
sd1.getPaint().setStyle(Style.STROKE);
sd1.getPaint().setStrokeWidth(1);
// sd1.getPaint().somehow_set_stroke_color?

ShapeDrawable sd2 = new ShapeDrawable(new RectShape());
sd2.getPaint().setColor(0xFF000000);
sd2.getPaint().setStyle(Style.STROKE);
// sd2.getPaint().somehow_set_stroke_color?
// sd2.getPaint().somehow_set_gradient_params?

layers[0] = sd1;
layers[1] = sd2;
LayerDrawable composite = new LayerDrawable(layers);
mMyImageView.setBackgroundDrawable(composite);

谢谢。

最佳答案

看来这不适用于ShapeDrawable,但请看我的GradientDrawable示例:

GradientDrawable gd = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.RED, Color.GREEN});
gd.setStroke(10, Color.BLUE);

您可能还需要以下方法:
gd.setGradientCenter(float x, float y);
gd.setGradientRadius(float gradientRadius);

10-08 18:03