Kotlin Enum 的 Android i18n 翻译问题

更新日期: 2021-10-01 阅读次数: 1772 字数: 248 分类: Android

我定义了一个 enum 类:

enum class ShelfLifeUnit {
    DAY, WEEK, MONTH, YEAR;

但是在真实项目中使用时,会发现如果要实现多语言版本,enum 不太好处理啊。。。

例如,在 Jetpack Compose 中,下拉列表的每一条对应一个 enum 项,需要使用不同翻译时:

ShelfLifeUnit.values().forEach { label ->
	DropdownMenuItem(onClick = {
		itemViewModel.setCurrentItem(item.copy(shelfLifeUnit = label), true)
	}) {
		Text(text = label.name)
	}
}

需要替换的是 label.name 部分

解决方法

enum class ShelfLifeUnit {
    DAY, WEEK, MONTH, YEAR;

    fun getLabel(context: Context): String {
        val res: Resources = context.resources
        val resId: Int = res.getIdentifier(name, "string", context.packageName)
        return if (resId == 0) {
            this.name
        } else {
            res.getString(resId)
        }
    }
}

然后在 composable 中使用:

val context = LocalContext.current

Text(text = label.getLabel(context))

但不要忘了将每个子项对应的大写单词加入 Android i18n 翻译

resId 为 0 的判断

找不到对应翻译资源时,会返回 0,最好是处理一下。

参考

  • https://stackoverflow.com/questions/9742050/is-there-an-enum-string-resource-lookup-pattern-for-android
  • 没有采用 string array 的方案,后会有期吧 https://developer.android.com/guide/topics/resources/string-resource

tags: Android i18n 国际化

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式