19

I am trying to change programmatically the color of the selectable_kachel_shape. Here is the xml file:

kachel_ticked_style.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >


    <item>
        <shape
            android:id="@+id/selectable_kachel_shape"
            android:shape="rectangle" >
            <stroke
                android:width="5dp"
                android:color="@color/headrbar_color" />
        </shape>
    </item>
    <item>
        <rotate
            android:fromDegrees="45"
            android:pivotX="120%"
            android:pivotY="100%"
            android:toDegrees="45" >
            <shape android:shape="line" >
                <stroke
                    android:width="40dp"
                    android:color="@color/headrbar_color" />
            </shape>
        </rotate>
    </item>
    <item
        android:right="5dp"
        android:top="5dp">
        <bitmap
            android:gravity="top|right"
            android:src="@drawable/selectable_tiles_check" />
    </item>

</layer-list>

I am calling inside a Fragment the following code

LayerDrawable layers = (LayerDrawable)  this.getActivity().getResources().getDrawable(R.drawable.kachel_ticked_style);

GradientDrawable shape = (GradientDrawable) (layers.findDrawableByLayerId(R.id.selectable_kachel_shape));
                       shape.setColor(this.getActivity().getResources().getColor(android.R.color.background_dark);

1.Why am I geting a NullPointerException in shape.setColor?

2.How would it be possible to change the color inside a shape, that is inside a layer list, programmatically?

Stam
  • 2,410
  • 6
  • 32
  • 58

1 Answers1

28

Ok I found the answer, I just had to put the id of the shape inside the item not in the shape kachel_ticked_style.xml:

<item 
    android:id="@+id/selectable_kachel_shape">
        <shape
             android:shape="rectangle" >
            <stroke
                android:width="5dp"
                android:color="@color/headrbar_color" />
        </shape>
    </item>

And then you can change either the color of the shape calling shape.setColor or the color of the stroke calling shape.setStroke(strokeWidth,strokeColor)

Stam
  • 2,410
  • 6
  • 32
  • 58
  • But am having the same problem.This doesnt work for me – jincy abraham Aug 02 '14 at 17:37
  • Well @jincyabraham you can get the view then its background drawable then get the shape as a gradiendrawable as in here [link](http://stackoverflow.com/questions/16636412/change-shape-solid-color-at-runtime-inside-drawable-xml-used-as-background) – M090009 Sep 21 '14 at 23:08
  • Can you please show what steps you did to acquire the the shape object, it is unclear. – basickarl Mar 13 '15 at 17:20
  • This works for a GradientDrawable, but not for a RotateDrawable which color I try to define at runtime. Any ideas? – Bobbelinio Oct 27 '15 at 15:28