首页 > 解决方案 > 是在 Kotlin 地图中作为整数或字符串检索的 Android 可绘制资源和字符串资源

问题描述

我在 Android 环境中学习 Kotlin 已经两天了。所以构建谷歌课程骰子应用程序我决定检查我是否可以通过将res/另一个values/文件夹添加到文件夹来本地化应用程序values-af_/。这是为了支持一种本地语言。

但问题是我想contentDescription使用ImageViewgetString(R.string.img_dice_1)方法设置 a 并将 a 设置setImageResource为 a R.drawable.image。这两个值都将包含在字典/地图/关联数组中,具体取决于骰子的掷骰。这是检查 num 变量是否为特定数字并检索资源的条件:

    val drawableRes = when (num) {
            1 -> mapOf("draw" to R.drawable.dice_1, "contDescription" to getString(R.string.img_dice_1))
            2 -> mapOf("draw" to R.drawable.dice_2, "contDescription" to getString(R.string.img_dice_2))
            3 -> mapOf("draw" to R.drawable.dice_3, "contDescription" to getString(R.string.img_dice_3))
            4 -> mapOf("draw" to R.drawable.dice_4, "contDescription" to getString(R.string.img_dice_4))
            5 -> mapOf("draw" to R.drawable.dice_5, "contDescription" to getString(R.string.img_dice_5))
            else -> mapOf("draw" to R.drawable.dice_6, "contDescription" to getString(R.string.img_dice_6))
        }

        imgOfDice.setImageResource(drawableRes["draw"] as Int)
        imgOfDice.contentDescription = (drawableRes["contDescription"] as Int).toString()

从地图中检索值时,logcat 会给出以下错误:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

如果我不将地图contDescription键转换为字符串,我会得到一个Compiling error: Type mismatch: inferred type is Int but CharSequence! was expected

有人可以指出我正确的方向来检索地图值吗?

我找到了答案:我只需drawableRes["contDescription"]要将 a 转换为 aCharSequence就可以了!

标签: androiddictionarykotlinandroid-drawableandroid-resources

解决方案


是的,您正在尝试将“draw”(字符串)转换为整数(R.drawable.x)

R.xx.xx 总是返回一个整数值(比如 ID)

val drawableRes = when (num) {
            1 -> mapOf(num to R.drawable.dice_1, "contDescription" to getString(R.string.img_dice_1))
            2 -> mapOf(num to R.drawable.dice_2, "contDescription" to getString(R.string.img_dice_2))
            3 -> mapOf(num to R.drawable.dice_3, "contDescription" to getString(R.string.img_dice_3))
            4 -> mapOf(num to R.drawable.dice_4, "contDescription" to getString(R.string.img_dice_4))
            5 -> mapOf(num to R.drawable.dice_5, "contDescription" to getString(R.string.img_dice_5))
            else -> mapOf(num to R.drawable.dice_6, "contDescription" to getString(R.string.img_dice_6))
        }
        imgOfDice.setImageResource(drawableRes[num] as Int)
        imgOfDice.contentDescription = (drawableRes["contDescription"] as Int).toString()

推荐阅读