android - 是在 Kotlin 地图中作为整数或字符串检索的 Android 可绘制资源和字符串资源
问题描述
我在 Android 环境中学习 Kotlin 已经两天了。所以构建谷歌课程骰子应用程序我决定检查我是否可以通过将res/
另一个values/
文件夹添加到文件夹来本地化应用程序values-af_/
。这是为了支持一种本地语言。
但问题是我想contentDescription
使用ImageView
该getString(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
就可以了!
解决方案
是的,您正在尝试将“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()
推荐阅读
- python - 如何创建条件无限 if 循环以将 XML 解析为 pandas 数据帧?
- c# - 将具有相同ID的多个字段统一为一个字段SQL Linq
- android - 按钮层问题(Android工作室)
- c++ - 为什么我没有得到任何输出(线性搜索)?
- angular - 角度发布工作第二次或第三次 HTTP Post
- javascript - 通过拖动指针填充 SVG
- java - 如何在 Kotlin 中添加 UTF-8 BOM?
- vue.js - 基于多个值的vue类绑定
- json - 使用 circe 编码为 JSON 的 StackOverflowError
- c# - Xamarin iOS SIGABRT 启动时崩溃