Search code examples
androidandroid-studiokotlinandroid-animationdrawable

How do I pass R.drawable.XXX value to a function in kotlin?


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!


Solution

  • R.drawable.whatever is just an Int. That's all you need to pass along to setBackgroundResource().

    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.

    private fun roomChange(@AnimRes animation: Int)
    {
        val rocketImage = findViewById<ImageView>(R.id.imageView2).apply {
            setBackgroundResource(animation)
            foxanim = background as AnimationDrawable
            foxanim.start()
        }
    }`