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?
CodePudding user response:
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.