问题描述
尝试学习一些新事物并且无法弄清楚这一点,我们将不胜感激.给出以下简单的代码,这些代码可以从Google文档中找到:
Trying to learn some new things and can't figure this one out, any help is appreciated. Given this simple code which is right from Google's documentation:
layers.xml:
layers.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/first_image">
<bitmap android:src="@drawable/android_red"
android:gravity="center" />
</item>
<item android:id="@+id/second_image" android:top="10dp" android:left="10dp">
<bitmap android:src="@drawable/android_green"
android:gravity="center" />
</item>
<item android:id="@+id/third_image" android:top="20dp" android:left="20dp">
<bitmap android:src="@drawable/android_blue"
android:gravity="center" />
</item>
</layer-list>
和main.xml:
<ImageView
android:id="@+myImageView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/layers" />
问题:如何以编程方式引用图层列表中的一个可绘制对象,以便可以将其更改为其他可绘制对象?
Question: How do I programmatically reference one of the drawables in the layer-list so I can change it to a different drawable?
谢谢.
所以现在我有了新的drawable,我想在变量myImage
中交换对吗?现在如何将其放入图层列表?我假设我使用findDrawableByLayerId
和setDrawableByLayerId
,但是究竟如何?否则我可能做错了!救命!
So now I have my new drawable that I want to swap in in variable myImage
correct? Now how do I get that into the layer-list? I assume I use findDrawableByLayerId
and setDrawableByLayerId
, but how exactly? Or I could be doing it completely wrong! Help!
我要做什么?更改显示的绘图.例如,假设我有另一个名为"android_purple"的可绘制对象,如何在上面的层列表示例中将其切换为"android_green"可绘制对象?
What am I trying to do? Change the drawable that's displayed. For example suppose I had another drawable called "android_purple", how would I switch it in for the "android_green" drawable in the layer-list example above?
据我所知,这是到目前为止的代码(不起作用起作用,出现setDrawableByLayerId
未定义的错误):
With my limited knowledge here is my code so far (which does not work, I get error that setDrawableByLayerId
is undefined):
Resources res = getApplicationContext().getResources();
BitmapDrawable newImage = (BitmapDrawable) res.getDrawable(R.drawable.android_purple); //Get replacement image, can't use LayerDrawable or get error.
boolean layer_drawable_changed = (setDrawableByLayerId((R.id.second_image), newImage)); //Set new drawable? Error on this line.
推荐答案
这是我会尝试的:
步骤1:将android:id
属性放在<item>
元素上,如图所示在文档中
Step #1: Put android:id
attributes on the <item>
elements as illustrated in the documentation
步骤2:将getDrawable()
结果转换为 LayerDrawable
Step #2: Cast the getDrawable()
result to a LayerDrawable
步骤3:如果您不想使用Drawable
影响其他任何人,请致电mutate()
(可能是可选的)
Step #3: Call mutate()
if you do not want to affect anyone else using the Drawable
(may be optional)
第4步:调用setDrawableByLayerId()
设置/替换给定层ID的Drawable
Step #4: Call setDrawableByLayerId()
to set/replace a Drawable
for a given layer ID
这篇关于如何更改图层列表可绘制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!