1

In Andoroid, I need to change a change a specific shape's color in a drawable xml with many shapes with colors dynamically. This drawable applied as a background to a Linearlayout

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/bandItem">
        <shape android:shape="rectangle">
            <solid
                android:id="@+id/bandColor" // Change This -->
                android:color="@color/band_traits" />
        </shape>
    </item>

    <item
        android:id="@+id/backgroundItem"
        android:left="10dp">
        <shape android:shape="rectangle">
            <solid
                android:id="@+id/backColor"
                android:color="@color/colorWhite" />
        </shape>
    </item>

</layer-list>

In the above drawable XML , I need to change the @color/colorGreen (marked above ) to needed color based on the condition.

I tried some stack overflow answers, but they are changing entire drawable. I need only to change the one marked as // Change this --->

Please help me !

(OR is it possible to design the above XML completely in Kotlin and apply as background object to a Linearlayout ?)

RagAnt
  • 1,064
  • 2
  • 17
  • 35
  • you can give ids to the item tag. I think through this you will be able to access and change colour dynamically – primo Oct 19 '22 at 06:46
  • 1
    Does this answer your question? [How to change a layer-list drawable?](https://stackoverflow.com/questions/8018435/how-to-change-a-layer-list-drawable) – TheLibrarian Oct 19 '22 at 06:58
  • @TheLibrarian This solved my issue. https://stackoverflow.com/a/32163988/9052139 – RagAnt Oct 19 '22 at 08:02

1 Answers1

1

Solved it

Retrieved the layer via it's ID and then retrieved the layer item via ID and then changed the color

private fun changeTagColor(holder: PropertyViewHolder, @ColorRes color: Int) {

    val ld = ContextCompat.getDrawable(
        context,
        R.drawable.side_band_property_card
    ) as LayerDrawable

    val gradientDrawable = ld.findDrawableByLayerId(R.id.bandItem) as GradientDrawable

    gradientDrawable.setColor(
        ContextCompat.getColor(
            context,
            color
        )
    ); // change color

    holder.mainLay.background = ld
}
RagAnt
  • 1,064
  • 2
  • 17
  • 35