4

I have a scenario where i need to have a large number of progress bar drawables. I cant create xml resources for all of them because i want the user to choose a color that will then be used to dynamically create the drawable. Below is one such drawable in xml, how can i create this exact drawable programmatically?

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid android:color="@color/transparent" />
        <stroke android:width="2px" android:color="@color/category_blue_stroke"/>
    </shape>
</item>


<item android:id="@android:id/progress">
<clip>
    <shape>
        <solid android:color="@color/category_blue" />
        <stroke android:width="2px" android:color="@color/category_blue_stroke"/>
    </shape>
</clip>
</item>

</layer-list>
kev
  • 890
  • 11
  • 26
  • 2
    This http://stackoverflow.com/a/8019888/1321873 should help you. – Rajesh Aug 02 '13 at 07:29
  • 2
    possible duplicate of [Create Custom Seekbar Programatically (No XML)](http://stackoverflow.com/questions/14510343/create-custom-seekbar-programatically-no-xml) – g00dy Aug 02 '13 at 07:31

1 Answers1

16

From the links provided by Rajesh and g00dy, i was able to come up with a solution.

public static Drawable createDrawable(Context context) {

ShapeDrawable shape = new ShapeDrawable();
shape.getPaint().setStyle(Style.FILL);
shape.getPaint().setColor(
    context.getResources().getColor(R.color.transparent));

shape.getPaint().setStyle(Style.STROKE);
shape.getPaint().setStrokeWidth(4);
shape.getPaint().setColor(
    context.getResources().getColor(R.color.category_green_stroke));

ShapeDrawable shapeD = new ShapeDrawable();
shapeD.getPaint().setStyle(Style.FILL);
shapeD.getPaint().setColor(
    context.getResources().getColor(R.color.category_green));
ClipDrawable clipDrawable = new ClipDrawable(shapeD, Gravity.LEFT,
    ClipDrawable.HORIZONTAL);

LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {
    clipDrawable, shape });
return layerDrawable;
}

This code will create a drawable that is visually similar to what the xml in my question creates.

kev
  • 890
  • 11
  • 26
  • 2
    You should also set ids `android.R.id.background` and `android.R.id.progress` (and `android.R.id.secondaryProgress` if needed) for the layers via `layerDrawable.setId(...)`. – kuelye Oct 17 '17 at 12:43