0

I trying to change the colours in this drawable dynamically.

The drawable xml is:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/status_colour_outer"
    android:bottom="4dp"
    android:left="4dp"
    android:right="4dp"
    android:top="4dp">
    <shape
      android:shape="oval">
      <solid android:color="@color/red"/>
    </shape>
  </item>
  <item android:id="@+id/status_colour_inner">
    <shape
      android:shape="oval">
      <stroke
        android:width="2dp"
        android:color="@color/red"/>
    </shape>
  </item>
</layer-list>

i need to change both the layers to the same colour dynamically from a webservice response.

The following code works only but only changes the

@+id/status_colour_inner

colour but doesn't change the outer yet it is referencing the layer:

    LayerDrawable layers = (LayerDrawable) ContextCompat.getDrawable(getContext(), R.drawable.status_colour);
    GradientDrawable shape = (GradientDrawable) layers.findDrawableByLayerId(R.id.status_colour_inner);
    GradientDrawable shape1 = (GradientDrawable) layers.findDrawableByLayerId(R.id.status_colour_outer);
    shape.setColor(Color.parseColor(mColours.getDisplayClasses().get(position).getColour()));
    shape1.setColor(Color.parseColor(mColours.getDisplayClasses().get(position).getColour()));
    aView.setBackground(layers);

mColours.getDisplayClasses().get(position).getColour()

all this does is return a String of the colour like "#B5FFC9"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Stillie
  • 2,647
  • 6
  • 28
  • 50

1 Answers1

0

try using the activity context to get the Drawable:

LayerDrawable layers = (LayerDrawable) ContextCompat.getDrawable(YourActivity.this,R.drawable.your_shape)
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • It works fine for the one layer, Inner layer but when i call GradientDrawable shape1 = (GradientDrawable) layers.findDrawableByLayerId(R.id.status_colour_outer); on the outer layer it doesnt apply that colour – Stillie Feb 28 '17 at 12:47
  • check [this](http://stackoverflow.com/questions/26561812/android-xml-layer-list-not-displayed-correctly-on-some-devices/26859663) never leave shapes with border without color as some devices will paint it black! – rafsanahmad007 Feb 28 '17 at 12:58