简体   繁体   English

Kotlin:如何在另一个变量的名称中插入一个变量的值

[英]Kotlin : How to insert a value of a variable in a name of another variable

Sadly, I failed to find any answer to this question on SO or elsewhere.可悲的是,我在 SO 或其他地方找不到这个问题的任何答案。

I am studying Kotlin and Android development and I wonder how I can insert a value of a variable in a name of another variable.我正在研究 Kotlin 和 Android 开发,我想知道如何在另一个变量的名称中插入一个变量的值。 Or if there is another, better solution to this problem I have.或者,如果我有这个问题的另一个更好的解决方案。

Suppose, my code looks like this:假设,我的代码如下所示:

...
 private fun rollDice() {
    // Create new Dice object with 6 sides and roll the dice
    val dice = Dice(6)
    val diceRoll = dice.roll()

    // Find the ImageView in the layout
    val diceImage: ImageView = findViewById(R.id.imageView)

    // Determine which drawable resource ID to use based on the dice roll
    val drawableResource = when (diceRoll) {
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }

    // Update the ImageView with the correct drawable resource ID
    diceImage.setImageResource(drawableResource)

    // Update the content description
    diceImage.contentDescription = diceRoll.toString()
}
...

I wonder if in the "Determine which drawable resource ID to use based on the dice roll" block I could actually use something like this (also, sorry, I don't know the correct syntax yet):我想知道在“根据掷骰子确定要使用的可绘制资源 ID”块中,我是否可以实际使用这样的东西(另外,抱歉,我还不知道正确的语法):

val drawableResource = R.drawable.{"dice_"+ diceRoll.toString()}

This way I could have saved much space and make the code easily extensible, if, for example, I had a 20-sided dice, I still would have needed this single line of code.这样我可以节省很多空间并使代码易于扩展,例如,如果我有一个 20 面的骰子,我仍然需要这一行代码。

Or else I would have needed to add否则我需要添加

when(diceRoll){ 
...
20 lines of code here
...
}

How can I solve this problem?我怎么解决这个问题? Thank you.谢谢你。

Thanks to Shlomi Katriel for linking the correct solution to this in comment on the original post.感谢 Shlomi Katriel 在对原始帖子的评论中将正确的解决方案链接到此。

A way to formulate my question in this context would be exactly as in linked post — "How to get a resource id with a known resource name?"在这种情况下提出我的问题的一种方法与链接帖子中的完全一样——“如何获取具有已知资源名称的资源 id?”

My solution code for this exact case (changed 2 blocks):我针对这种情况的解决方案代码(更改了 2 个块):

// Determine which drawable resource ID to use based on the dice roll
val drawableResourceId : Int = this.resources.getIdentifier("dice_$diceRoll", "drawable",this.packageName)

// Update the ImageView with the correct drawable resource ID
diceImage.setImageResource(drawableResourceId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM