我有一个 wordList 名称的 mapOf 名称,我正在从中获取随机键。我有一个控制按钮,当用户单击该按钮时,我想从我的 mapOf 控制这些随机键。我该如何控制?
val wordList = mapOf("onekey" to "onevalue" , "twokey" to "twovalue" , "threekey" to "threevalue")
您可以通过创建一个从地图中获取随机密钥的函数来实现这一点
fun getRandomKey(map: Map<String, String>): String? {
if (map.isEmpty()) return null
val keys = map.keys.toList()
return keys.random()
}
设置一个onClickListener,点击按钮时调用getRandomKey,并显示随机key及其值
val controlButton: Button = findViewById(R.id.controlButton)
controlButton.setOnClickListener {
val randomKey = getRandomKey(wordList)
randomKey?.let {
Toast.makeText(this, "Random Key: $randomKey, Value: ${wordList[randomKey]}", Toast.LENGTH_SHORT).show()
}
}