首页 > 解决方案 > 我应该使用什么样的数组或列表来完成我的随机化代码?

问题描述

    button.setOnClickListener {
        //???
        val rand = Random().nextInt()
        phrase.text=rand.toString()}

到目前为止,这是我的代码,但我似乎找不到适合的数组或 listOf,它似乎总是以错误告终,代码有问题吗?我的目标是编写几个短语,单击按钮后将随机选择这些短语。

标签: javaandroidandroid-studiokotlinrandom

解决方案


如果我正确理解了你的问题,你可以使用类似的东西:

val random = Random(System.currentTimeMillis())
val list : List<String> = (1..10).map {
    random.toString()
}

// now you can set the list of strings to whatever you want
// if you have an array of TextViews...

list.forEachIndexed { index, phrase ->
    phrasesTextViews[index].text = phrase
}

但是如果你想要一个字符串中的所有短语:

phrasesTextView.text = (1..10).map { it.toString() }.joinToString(", ")

推荐阅读