mercredi 22 avril 2020

Select distinct random images in Kotlin

I have an issue about Kotlin code, I have a task where I have to generate images randomly from an array, but the thing is that they have to be distinct from each other. There are four images views and after clicking on them, one of those Views has to change its source randomly. I have wrote this code, but the images are not distinct

class MainActivity : AppCompatActivity(), View.OnClickListener {

private val images = arrayOf(
    R.mipmap.fruit,
    R.mipmap.banana,
    R.mipmap.watermelon,
    R.mipmap.apricot,
    R.mipmap.cherry,
    R.mipmap.strawberry,
    R.mipmap.melon,
    R.mipmap.kiwi
)
private lateinit var imageViews:Array<ImageView>


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    init()

}

private fun init() {

    imageViews = arrayOf(imageView_1, imageView_2, imageView_3, imageView_4)
    imageView_1.setOnClickListener(this)
    imageView_2.setOnClickListener(this)
    imageView_3.setOnClickListener(this)
    imageView_4.setOnClickListener(this)
}







override fun onClick(v: View?) {
    randomImageView().setImageResource(randomImage())
}



private fun randomImage() = images[(images.indices).random()]
private fun randomImageView() = imageViews[(imageViews.indices).random()]

}




Aucun commentaire:

Enregistrer un commentaire