更改ImageView源 [英] Changing ImageView source
问题描述
我有一个 ImageView
,使用以下语法在xml中设置源图像:
I have an ImageView
with a source image set in the xml using the following syntax:
<ImageView
android:id="@+id/articleImg"
style="@style/articleImgSmall_2"
android:src="@drawable/default_m" />
现在我需要以编程方式更改此图像。我需要做的是删除旧图像并添加一个新图像。我所做的是:
Now I need to change this image programmatically. What I need to do is delete the old image and add a new one though. What I have done is this:
myImgView.setBackgroundResource(R.drawable.monkey);
它有效但我注意到android将新图像堆叠在旧图像之上(不要问我怎么做我发现它与讨论无关:)。在设置新图像之前,我绝对需要摆脱旧版本。
It works but I noticed android stacks the new image on top of the old one (dont ask me how I found out it's not relevant for the discussion :). I definitely need to get rid of the old one before setting the new image.
我怎样才能实现这一目标?
How can I achieve that?
推荐答案
更改ImageView源:
使用 setBackgroundResource()
方法:
myImgView.setBackgroundResource(R.drawable.monkey);
你把那只猴子放在后台。
you are putting that monkey in the background.
我建议使用 setImageResource()
方法:
I suggest the use of setImageResource()
method:
myImgView.setImageResource(R.drawable.monkey);
或 setImageDrawable()
方法:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
***使用新的android API 22 getResources()。getDrawable()
现已弃用。这是一个如何立即使用的示例:
*** With new android API 22 getResources().getDrawable()
is now deprecated. This is an example how to use now:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
以及如何验证旧API版本:
and how to validate for old API versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}
这篇关于更改ImageView源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!