Change <layer-item> elements with Java code

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 "customPlayerProgress" and "customPlayerProgressSecondary" with Java code. How can I do that?

+6
source share
3 answers

Assuming you want to access them through Java code after they are loaded as Drawable into your application, you can 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 one for more ideas.

+8
source

You cannot modify the generated XML files at run time.

+1
source

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

Here is an article that might be helpful.

0
source

Source: https://habr.com/ru/post/906691/


All Articles