Search code examples
androidandroid-drawablexml-drawable

Create Layer-list with rotated shape programmatically


I am currently trying to convert the following XML to be created programmatically so I can play on the shape color programmatically without harding coding 3 different same shape with different color.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/secondaryProgress">
    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="14.0"
        android:useLevel="true">

        <solid android:color="@android:color/transparent" />
    </shape>
</item>
<item android:id="@android:id/progress">
    <rotate
        android:fromDegrees="270"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="270">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="14.0"
            android:useLevel="true">

            <corners android:radius="10dp" />
            <rotate
                android:fromDegrees="0"
                android:pivotX="50%"
                android:pivotY="50%"
                android:toDegrees="360" />
            <solid android:color="@color/custom_color0" />
            <stroke
                android:width="1dip"
                android:color="@color/custom_color0" />
        </shape>
    </rotate>
</item>


Solution

  • I had some problem. While searching for it found your post unanswered so i would like share my solution with you. May be it can help you.

    I created a layer-list drawable and changed its items color dynamically. Here is the code:

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:id="@+id/item_bottom_stroke" >
        <shape android:shape="rectangle">
            <solid android:color="#0096FF"/>
        </shape>
    </item>
    <item android:id="@+id/item_navbar_background" android:bottom="1dp" >
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF"/>
        </shape>
    </item>
    

    Following code modifies above drawable at runtime to change its colors.

    LayerDrawable layerDrawable = (LayerDrawable) v.getContext().getResources().getDrawable(R.drawable.layer_list_navigation_with_border);
    GradientDrawable strokeDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_bottom_stroke);
    strokeDrawable.setColor(strokeColor[0]);
    GradientDrawable backgroundColor = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.item_navbar_background);
    backgroundColor.setColors(bgColor);