Here’s my code:
private fun roomChange(animation: Int)
{
val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
setBackgroundResource(R.drawable.animation)
foxanim = background as AnimationDrawable
foxanim.start()
}
}
I have anim.xml file and would like to pass it to a function but "animation" is an unresolved reference. How would I go about passing it correctly? Thanks in advance!
3
Answers
R.drawable.whatever
is just an Int. That’s all you need to pass along tosetBackgroundResource()
.If you want the IDE to help prevent you from accidentally passing the wrong kind of argument, you can also add
@AnimRes
. Then in certain cases when it can detect that you are passing an Int that is not an animation resource ID, it will show an error.Modify your code like this :
Here’s the enum thing I mentioned in the comments:
The idea here is you can create an enum class that defines all your animations, so you can name each one however you like, and they all have a resource ID for the animation they represent. Then you pass one of those to your function instead, and the function can refer to its resource ID
This way you get code completion and type checking (you have to pass one of the
StateAnimation
s, not any other animation ID, resource ID, or random int). Your code can be cleaner becauseStateAnimation.RUN
is pretty clear (you might want to rename that but you get the idea), and it’s safer than passing a string like"run"
and converting that into a resource lookup which may or may not existAnd if you want, you can just
import
everything inStateAnimation
(put your cursor onRUN
and doAlt+Enter
or click the lightbulb and it’ll offer to do it for you) and then you can just callroomChange(RUN)
and it’s nice and concise!