更改 ImageView 源

编程入门 行业动态 更新时间:2024-10-27 13:27:10
本文介绍了更改 ImageView 源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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 源

本文发布于:2023-07-11 11:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ImageView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!