How to change a layer-list drawable?

六月ゝ 毕业季﹏ 提交于 2019-11-26 15:59:58

Question: How do I programmatically reference one of the drawables in the layer-list so I can change it to a different drawable?

Here's what I would try:

Step #1: Put android:id attributes on the <item> elements as illustrated in the documentation

Step #2: Cast the getDrawable() result to a LayerDrawable

Step #3: Call mutate() if you do not want to affect anyone else using the Drawable (may be optional)

Step #4: Call setDrawableByLayerId() to set/replace a Drawable for a given layer ID

Kavita

Step 1:Retrieve the Layer-list from the drawable folder: (Mine was called digits at /res/drawable/digits.xml)

LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.digits);

Step 2: Name the replacing image (not the the image already in layer-list)

Drawable replace = (Drawable) getResources().getDrawable(R.drawable.replacing_image);

Step 3: Replace the Image using the setDrawableByLayerId(int id, Drawable d) method

boolean testfactor = ld.setDrawableByLayerId(R.id.first_image, replace);

This returns a boolean value that will return false if replacing the image failed

Step 4: Load main Imageview (basically id of layer-list in the actual xml layout code)

ImageView layoutlist1 = (ImageView)findViewById(R.id.layout_list1);

Step 5: (re)-Set the Imageview with your updated LayerDrawable by saying:

layoutlist1.setImageDrawable(ld);

RESOURCES: I'm a software and mobile app developer.

I looked all over the web and alot of Stackflow.com in order to get to this point. All the answers were like the ones that were already on this page. I was trying to do the same thing. Then I thought about the idea of "updating the image" and came to this.

This should/can also work for when you want to put a Bitmap in place of one the items on your list. You just have to use the replace (setDrawableByLayerId) method. to replace on ids. ImageView has a lot of methods.

This was also helpful: LayerList drawable + conversion to a Bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!