Search code examples
androidarrayskotlinrandomandroid-image

How to detect which element of array is shown in imageView?


I want to randomly set resource in imageView and after that, check which element in an array is shown. How it could be possible? I'm a beginner.

var three = intArrayOf(R.drawable.na3,R.drawable.na4)
    image_view.setImageResource(three[random.nextInt(three.size)])
                if (three[1]){
                //Do stuff
                }

In "three[1]" I'm getting error:

Type mismatch. Required: Boolean Found: Int


Solution

  • You can do like this.

     val arrayList = listOf(R.drawable.ic_launcher_background1,R.drawable.ic_launcher_background2,R.drawable.ic_launcher_background3)
        val randomNumber = Random().nextInt(arrayList.size)
    
        imageView.setImageResource(arrayList[randomNumber])
        when (randomNumber){
            0-> println("Index is 0")
            1-> println("Index is 1")
            2-> println("Index is 2")
            else->
                println("Error")
    
    }