Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change color of shape in layer list

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> 
like image 743
user Avatar asked Aug 23 '15 06:08

user


2 Answers

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">     <item android:id="@+id/gradientDrawble"> // Give id         <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> 

Then in you code just add

LayerDrawable layerDrawable = (LayerDrawable) getResources()             .getDrawable(R.drawable.my_drawable); GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable             .findDrawableByLayerId(R.id.gradientDrawble); gradientDrawable.setColor(color); // change color 

Update Oct-2016

getDrawable() is now deprecated, you should use ContextCompat.getDrawable(context, color) instead.

Beside, if you get the LayerDrawable by findDrawableByLayerId(), then you had to call view.setBackground(layerDrawable) for this to take effect. Alternatively, instantiating the layerDrawable by view.getBackground() also worked.

like image 74
Suhail Mehta Avatar answered Sep 24 '22 03:09

Suhail Mehta


First of all you need to assign id to you layer-list item.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- First assign id to the list item-->     <item  android:id="@+id/your_shape">           <shape android:shape="rectangle">             <solid android:color="#000000" />          </shape>     </item>     <item android:left="5dp">         <shape android:shape="rectangle">             <solid android:color="@color/bg" />         </shape>     </item> </layer-list> 

Then get your shape by id.

LayerDrawable shape = (LayerDrawable) getResources().getDrawable(R.drawable.your_shape) 

And you can change the color of your shape by calling

shape.setColor(Color.Black); // changing to black color 

EDIT

As getDrawable() has been deprecated. Use the following line of code.

LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(YourActivity.this,R.drawable.your_shape) 
like image 43
Noman Rafique Avatar answered Sep 26 '22 03:09

Noman Rafique