问题描述
我有以下XML资源$ C $ C,它是卡项目的列表
I have the following xml resource code that is a background layout for a list of card items
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CABBBBBB"/>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp"
android:drawable="@drawable/kpop">
<shape android:shape="rectangle">
<solid android:color="#151B54"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
我的问题是,我想以编程方式更改绘制资源
My problem is that I would like to change the drawable resource programmatically
android:drawable="@drawable/kpop"
(使每个卡产品将有不同的背景图像)
(so that each card item would have a different background image)
任何想法/提示,我该怎么办呢?
Any idea/tip how I can do that?
推荐答案
下面是你如何能做到这一点:
Here is how you can achieve that:
-
获取对图层列表的引用
Obtain a reference to your layer-list
LayerDrawable层=(LayerDrawable)yourView.getBackground();
的或者的
LayerDrawable层=(LayerDrawable)context.getResources()getDrawable(R.id.yourLayerDrawable);
创建图层绘制的新实例内部
Create a new instance of the layer drawable internally
layer.Mutate();
Android的内部缓存可绘制,这意味着,如果通过上述方法修改绘制obtaind,所有其他可绘将受到影响。以prevent,你可以调用告诉系统保留绘制的单独副本,这样就不会影响到其他绘图资源。
Android internally caches drawables, which means that if you modify a drawable obtaind through the above method, all other drawables will be affected. To prevent that, you can call Drawable.Mutate() to tell the system to retain a separate copy of the drawable so that it won't affect the other drawables.
有关项目集标识进行修改
Set id for item to be modified
机器人:ID =@ + ID / image_background
这样的:
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp"
android:id="@+id/image_background" <----
android:drawable="@drawable/kpop">
<shape android:shape="rectangle">
<solid android:color="#151B54"/>
<corners android:radius="2dp" />
</shape>
</item>
设置/重置绘制该项目
layer.setDrawableByLayerId(R.id.image_background,yourNewDrawable);
重绘层
layer.invalidateSelf();
这篇关于以编程方式更改绘制资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!