我如何控制我的特定mapOf元素?

问题描述 投票:0回答:1

我有一个 wordList 名称的 mapOf 名称,我正在从中获取随机键。我有一个控制按钮,当用户单击该按钮时,我想从我的 mapOf 控制这些随机键。我该如何控制?

val wordList = mapOf("onekey" to "onevalue" , "twokey" to "twovalue" , "threekey" to "threevalue")
android kotlin
1个回答
0
投票

您可以通过创建一个从地图中获取随机密钥的函数来实现这一点

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()
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.