Android drawable layer set color fails

155 views Asked by At

I am trying to change the color of a layer in my drawable programmatically, so the actual drawable xml file would not change, but just the current drawable that is used as an src in my ImageView.

The object I am working with is a 3 circles (3 oval shapes) nested inside each other (see card_template.xml) below.

I have the following code:

    LayerDrawable cardLayers = (LayerDrawable) keyCard.getDrawable();
    System.out.println("Number of layers (should be 3): "+ cardLayers.getNumberOfLayers());
    GradientDrawable layer1 = (GradientDrawable) (cardLayers.findDrawableByLayerId(R.id.card_layer1));
    layer1.setColor(0);

I know I'm getting the correct drawable, because of the System.out.println value, but when I set the color of the layer in layer1.setColor(0);, the layer just disappears - the outer circle is not shown in the keyCard ImageView anymore.

Neither layer1.setColorFilter(0, PorterDuff.Mode.___) is not working in any mode, the layer either stays the same or disappears..

Why is this happening? I couldn't find my solution not in docs, and not in any question here or elsewhere.

Please help :)

Here is card_template.xml:

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/card_layer1">
    <shape android:shape="oval">
        <solid android:color="@android:color/black"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <size
            android:width="5dp"
            android:height="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </shape>
</item>
<item android:id="@+id/card_layer2" android:top="2dp" android:left="2dp" android:right="2dp" android:bottom="2dp">
    <shape android:shape="oval">
        <solid android:color="#ff0000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <size
            android:width="5dp"
            android:height="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </shape>
</item>

<item android:id="@+id/card_layer3" android:top="4dp" android:left="4dp" android:right="4dp" android:bottom="4dp">
    <shape android:shape="oval">
        <solid android:color="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <size
            android:width="5dp"
            android:height="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </shape>
</item>

1

There are 1 answers

1
m.rohail.akram On

According to GradientDrawable documentation setColor takes ColorStateList.

Please go through ColorStateList to learn more. try and give an appropriate colorstate object instead of 0.