29

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?

ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89

1 Answers1

62

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(----);
ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89
  • 3
    Do you have any idea how to implement the same on RemoteView for widgets? Thanks. – stuckedunderflow Jun 06 '14 at 06:31
  • @MV1 This is possible in remote view. Because its not working. Can u guide me http://stackoverflow.com/questions/24545857/how-to-change-remote-view-background-in-runtime?noredirect=1#comment38013228_24545857 – RED.Skull Jul 03 '14 at 05:54
  • @ʞᴉɯ Could you help with a similar question just with ImageButtons: http://stackoverflow.com/questions/35398658/change-the-shape-color-of-a-imagebutton/35399878#35399878 –  Feb 15 '16 at 12:03