1

I defined an Android Drawable like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="oval">
            <solid android:color="@android:color/transparent" />
            <stroke android:width="8dp" android:color="@android:color/white" />
        </shape>
    </item>
    <item android:left="2dp" android:bottom="2dp" android:right="2dp" android:top="2dp">
        <shape android:shape="oval">
            <solid android:color="@android:color/transparent" />
            <stroke android:width="4dp" android:color="@android:color/black" />
        </shape>
    </item>

</layer-list>

In code I get the drawable from the resources and use it while painting on a canvas (SurfaceView.draw).

Drawable dr = context.getResources().getDrawable(R.drawable.circle_empty);

@Override
public void draw(Canvas canvas) {

        // how to set the color?
        dr.draw(canvas);
}

But I wonder, how I could change the color of the drawable in code? For instance get a green or red ring instead of the black one as defined in XML.

Matthias
  • 5,574
  • 8
  • 61
  • 121
  • You're welcome. But dig a little more, before posting a question. In order to avoid duplicates. – Phantômaxx Jul 30 '14 at 12:40
  • You're right. I tried to find a post. But "Changing color in a shape inside a layer-list programmatically" would not have occurred to me as a suitable post to me. – Matthias Jul 30 '14 at 12:44
  • Well, it took me 5 seconds on Google to find the StackOverflow question... – Phantômaxx Jul 30 '14 at 13:09

1 Answers1

0

Try something like this:

   LayerDrawable layerDrawable= (LayerDrawable) context.getResources().getDrawable(R.drawable.circle_empty);
    GradientDrawable gradientDrawable= (GradientDrawable)layerDrawable.getDrawable(1);
    gradientDrawable.setStroke(4, Color.GREEN);
vipul mittal
  • 17,343
  • 3
  • 41
  • 44