遗憾的是,我在网上或其他地方都找不到这个问题的任何答案.

我正在研究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
...
}

我怎么才能解决这个问题呢? 谢谢.

推荐答案

感谢Shlomi Ktriel在 comments 最初的帖子时将正确的解决方案链接到这个问题上.

在这种情况下,表达我的问题的一种方法与链接帖子中的"如何使用已知的资源名称获取资源ID?"

My solution code for this exact case(更改了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)

Android相关问答推荐

写入排除例外以进行依赖性判断

如何在Android中使用TextView设置动态文本的样式

在不增加父行宽度的情况下添加延迟行或可滚动行

Kotlin Android VS Kotlin多平台

从我的 Android 应用程序发送到 Gin 时失败,但从 Postman 发送到 Gin 时成功

页面标题未显示在内容页面上

如何禁用自动登录 google play games services android unity?

在 Android 房间迁移中获取上下文

需要在按钮 onclick 上从 string.xml 获取值. @Composable 调用只能在@Composable 函数的上下文中发生

围绕动态大小的内容包装 Jetpack Compose Row?

从 Jetpack Compose 中的 IconButton 中删除黑色色调

LazyColumn 项目,隐式接收器无法在此上下文中调用单元

如何放置在柱子的角落(底端)

我不能在 jetpack Compose 中使用 TextField()(material 3)

在 Kotlin 中打开新片段时如何对当前片段应用更改?

协程中的 Job.Cancel 与 Scope.Cancel 有什么区别?

Jetpack 组合和片段

操作系统会终止已启动的服务并调用Service.onDestroy吗?

AndroidX Room 生成类错误:类是公共的,应在名为 class.java 的文件中声明

lambda 函数中的类型不匹配 - Kotlin