How can I programmatically change the color (#000000
) of a shape in a layer list?
Here is my layer list:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#000000" /> // CHANGE THIS COLOR
</shape>
</item>
<item android:left="5dp">
<shape android:shape="rectangle">
<solid android:color="@color/bg" />
</shape>
</item>
</layer-list>
You can also get the drawable or background of the view and set it as follows.
First of all you need to assign id to you
layer-list
item.Then get your shape by id.
And you can change the color of your shape by calling
EDIT
As
getDrawable()
has been deprecated. Use the following line of code.Find your view
Set color
Then in you code just add
Update Oct-2016
getDrawable()
is now deprecated, you should useContextCompat.getDrawable(context, color)
instead.Beside, if you get the
LayerDrawable
byfindDrawableByLayerId()
, then you had to callview.setBackground(layerDrawable)
for this to take effect. Alternatively, instantiating thelayerDrawable
byview.getBackground()
also worked.