Pranciskus
Pranciskus

Reputation: 539

How to apply random list of numbers for selection from array to select image?

How to make list of random numbers and use it to set image from array?

val randomValues = List(15) { Random.nextInt(0, 5) }
var array = intArrayOf(R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5)
imageView.setImageResource(array[randomValues])

I'm getting Type mismatch on randomValues in imageView.setImageResource(array[randomValues]). Required: Int and Found: List <int>.

Edited

val randomValues = List(15) { Random.nextInt(0, 5) }
        var array = intArrayOf(R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5)


        imageView.setOnClickListener {
            randomValues
                .map { array[it] }
                .forEach { imageView.setImageResource(it) }
        }

Upvotes: 0

Views: 388

Answers (2)

gpunto
gpunto

Reputation: 2832

If you want to select a new random image at each click you just need to do:

val array = intArrayOf(R.drawable.cat1, R.drawable.cat2, R.drawable.cat3, R.drawable.cat4, R.drawable.cat5)


imageView.setOnClickListener {
    imageView.setImageResource(array.random())
}

If you absolutely need to use a predefined list of random values (what's the point?), then you need to track the last index you used. Something like:

// in your class
var lastIndex = 0
val randomValues = List(15) { Random.nextInt(0, 5) }

// setting the listener
val array = intArrayOf(R.drawable.cat1, R.drawable.cat2, R.drawable.cat3, R.drawable.cat4, R.drawable.cat5)

imageView.setOnClickListener {
    imageView.setImageResource(array[randomValues[lastIndex]])
    lastIndex = (lastIndex + 1) % randomValues.size
}

Upvotes: 2

jsamol
jsamol

Reputation: 3232

If you'd like to select simply a random element from the array, you can use the Array.random() method which just returns a random element from the array:

var array = intArrayOf(R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5)
imageView.setImageResource(array.random())

Edit

If you want to select a list of resources based on a randomly generated list of indices, you can achieve this by transforming every index into the right resource. Then you can perform your action on every selected item using the forEach method:

var array = intArrayOf(R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5)
val randomValues = List(15) { Random.nextInt(0, 5) }

randomValues
    .map { array[it] }
    .forEach { imageView.setImageResource(it) }

Basically your approach failed because you tried to use the entire randomValues list as a single index value. Instead you should iterate over the list in one way or another and select the resource for each randomly generated number.

Upvotes: 1

Related Questions