我有一个 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() 方法:
or with setImageDrawable() method:
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 源
发布评论