Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change shape solid color at runtime inside Drawable xml used as background

I've a Drawable xml file (background.xml):

<?xml version="1.0" encoding="UTF-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >     <item>         <shape>          ...........         </shape>     </item>      <item android:id="@+id/shape_id">         <shape android:shape="rectangle">             <solid android:color="#ffefefef" />          </shape>     </item>  </layer-list> 

used by a LinearLayout:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:background="@drawable/background"     android:id="@+id/layout_id"     > 

Now i need to change the shape shape_id solid color at runtime based on some conditions. How to do this?

like image 785
ʞᴉɯ Avatar asked May 19 '13 15:05

ʞᴉɯ


People also ask

How do I change the background color of drawable?

This example demonstrates how to change the colors of a Drawable in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I change the color of a drawable in xml?

Use app:drawableTint="@color/yourColor" in the xml instade android:drawableTint="@color/yourColor" . It has the backward compatibility.

How do you put a background color in a shape?

With the shape still selected, click the Fill Color button. Select a color for the background. You can enter the Hex or RGB values. Use the slider underneath the color selection to change the background opacity.


1 Answers

Found by me:

    View v = findViewById(R.id.layout_id);      LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();     final GradientDrawable shape = (GradientDrawable)   bgDrawable.findDrawableByLayerId(R.id.shape_id);     shape.setColor(----); 
like image 72
ʞᴉɯ Avatar answered Oct 08 '22 19:10

ʞᴉɯ