为什么您可以直接更改ImageView的srccompat?
我正在关注Kotlin Android教程,目前正在Dice Roller应用程序教程中。为了更改图像,教程说要写:
diceImage.setImageResource(drawableResource)
我的问题是,为什么我们不能直接更改图像?就像说:
diceImage.srcCompat = drawableResource
我认为我们不能这样做的原因可能是srccompat变量是私人的,但是后来教程写道:
diceImage.contentDescription = diceRoll.toString()
内容描述在与srccompat的“常见属性”标签下,这可能意味着srccompat issn'' t私人。虽然我可能错了。
我的问题是:
为什么我们不能直接设置SRCCOMPAT?
SetImageresource函数的确切作用是什么?
I am following the Kotlin Android tutorial and am currently on the Dice Roller App tutorial. For changing the image, the tutorial says to write:
diceImage.setImageResource(drawableResource)
My question is, why can't we change the image directly? Like say:
diceImage.srcCompat = drawableResource
I thought that maybe the reason we couldn't do that was that the srcCompat variable was private, but later the tutorial writes:
diceImage.contentDescription = diceRoll.toString()
The content description is under the same "common attributes" tab as srcCompat, which probably means srcCompat isn't private. Although I'm probably wrong.
My questions are:
Why can't we set srcCompat directly?
What is the setImageResource function doing exactly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在ImageView内部,实际图像是可绘制的。当您设置Immageresource时,您将设置一个INT ID。然后,图像视图将通过调用Context.Resources.getDrawable(ID)查找与ID相关联的内容,并将其保存在变量中。因此,您不能仅仅通过属性集进行操作,因为您存储的值与将其设置为的值不同。因此,您需要一个功能。
请注意,您可以在图像上设置图像的几种不同方法 - 从可绘制的资源ID,位图等。如果您有多种方式,则需要是函数而不是属性。 ContextDeScription可以起作用,因为您只将其设置为charsequence。
Inside the ImageView, the actual image is a Drawable. When you setImageResource, you're setting an int id. The ImageView will then look up what Drawable is associated with the id by calling context.resources.getDrawable(id) and save that in a variable. So you can't just do it via a property set, because the value you'd be storing isn't the same type as the value you'd be setting it to. Thus you need a function.
Notice there are several different ways you can set the image on an image view- from a Drawable, a resource id, a Bitmap, etc. If you have more than one way, it needs to be a function and not a property. ContextDescription can work because you're only ever setting it to a CharSequence.