Im trying to display random image whenever the app goes on. First I made a list with image ids and tried to make a random integer so that I can get random image each time by using the integer as an index of the list. Below is the code I tried.
val background_image = findViewById<ImageView>(R.id.background_image)
val drawableList = mutableListOf<Int>(R.drawable.picture_0001,R.drawable.picture_0002,R.drawable.picture_0003)
val index = Random.nextInt(drawableList.size)
val test = (1..5).random()
Toast.makeText(this,test.toString(),Toast.LENGTH_SHORT).show()
background_image.setImageResource(drawableList[index])
test
and the Toast
part is just for checking if other random method works.
but both two ways doesn't work and shows the same random integer every time. Why isn't it working?
(minSDK 21).
CodePudding user response:
Instead of generating a random number on your own, you can simply use the extension function of Collection
class.
val list = mutableListOf(1,2,3,4,5,6,7)
val aRandomNumberFromList = list.random()
CodePudding user response:
You need to use a different seed to get different results.
from Random
Two generators with the same seed produce the same sequence of values within the same version of Kotlin runtime.
You can use System.currentTimeMillis()
as a seed.
val random = Random(System.currentTimeMillis())
val list = listOf(1,2,3)
val randomInt = list[random.nextInt(list.size)]