遗憾的是,我在网上或其他地方都找不到这个问题的任何答案.
我正在研究Kotlin和Android开发,我想知道如何将一个变量的值插入另一个变量的名称中.或者,如果我有其他更好的解决这个问题的办法.
假设我的代码如下所示:
...
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()
}
...
我想知道如果在 "Determine which drawable resource ID to use based on the dice roll"个 块我实际上可以使用类似这样的东西(另外,对不起,我还不知道正确的语法):
val drawableResource = R.drawable.{"dice_"+ diceRoll.toString()}
这样,我可以节省很多空间,并使代码易于扩展,例如,如果我有一个20面的骰子,我仍然需要这一行代码.
否则我就需要加上
when(diceRoll){
...
20 lines of code here
...
}
我怎么才能解决这个问题呢? 谢谢.