6

I have the following XML:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/customPlayerProgressBg">
    <shape>
        <gradient
                android:startColor="#FF999999"
                android:endColor="#FF999999"
        />
    </shape>
</item>

<item android:id="@+id/customPlayerProgressSecondary">
    <clip>
        <shape>
            <gradient
                    android:startColor="#FF5C3C68"
                    android:endColor="#FF5C3C68"
            />
        </shape>
    </clip>
</item>
<item
    android:id="@+id/customPlayerProgress"
>
    <clip>
        <shape>
            <gradient
                android:startColor="#FF5C3C68"
                android:endColor="#FF5C3C68"
            />
        </shape>
    </clip>
</item>

</layer-list>

I want to change the "customPlayerProgress" and the "customPlayerProgressSecondary" by Java code. How can that be accomplished?

Jonik
  • 74,291
  • 66
  • 249
  • 356
Alesqui
  • 6,265
  • 5
  • 33
  • 41
  • Possible duplicate of [How to change a layer-list drawable?](http://stackoverflow.com/questions/8018435/how-to-change-a-layer-list-drawable) – Jonik Jun 07 '16 at 15:21

3 Answers3

9

Assuming that you want to have access to them through Java code after they are loaded as a Drawable in your app, you should be able to do something like the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.my_drawable);
    final ClipDrawable d1 = (ClipDrawable) ld.findDrawableByLayerId(R.id.customPlayerProgress);
    final ClipDrawable d2 = (ClipDrawable) ld.findDrawableByLayerId(R.id.customPlayerProgressSecondary);

    /* modify ld, d1 and d2 by calling their methods here */
}

Also look at this for some more ideas.

Community
  • 1
  • 1
Joe
  • 13,858
  • 2
  • 37
  • 49
  • Worked. R.id.customPlayerProgress was not being recognized, i had to rebuild the project (Project > Clean, then Build). – voghDev Sep 05 '14 at 23:43
  • It seems that "getResources().getDrawable(R.drawable.my_drawable)" doesn't return the same object that can be obtained in code. Isn't it better to get LayerDrawable object using "view.getBackground()" ? – Ehsan Heidari Sep 18 '17 at 12:22
1

You can't change generated XML files at run-time.

Cody
  • 8,061
  • 17
  • 65
  • 120
0

You may be familiar with DOM. You just need to modify the change and then save the file.

Here is an article that may be of some assistance.

prolink007
  • 30,784
  • 21
  • 111
  • 173