android - 如何应用随机数字列表从数组中选择图像?

标签 android arrays list kotlin random

如何制作随机数列表并使用它来设置数组中的图像?

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])

我在randomValues中的imageView.setImageResource(array[randomValues])上遇到类型不匹配的问题。 Required: Int and Found: List <int>

已编辑
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) }
        }

最佳答案

如果您想在每次单击时选择一个新的随机图像,则只需执行以下操作:

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


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

如果绝对需要使用预定义的随机值列表(这是什么意思?),则需要跟踪使用的最后一个索引。就像是:
// 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
}

关于android - 如何应用随机数字列表从数组中选择图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524217/

相关文章:

安卓ViewPager : Scroll to next item only when the previous item is scrolled to 90%

android - 如何使用 KitKat 在 WebView 中使文本适合屏幕(文本换行)

java - Android IntentService无法启动通知

c - 使字符串中的一个单词大写,C编程

c# - 将字符串转换为列表 - C#

Java比较两个List的对象值?

Android 定期运行任务

arrays - WebKitView请求没有通过?

有很多 [char array ] 问题的 C 结构

r - 如何减少 R 列表中的值