更改ImageView源

编程入门 行业动态 更新时间:2024-10-27 15:15:45
本文介绍了更改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() 方法:

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

发布评论

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

>www.elefans.com

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