You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android枚举类humanName多语言翻译配置问题

解决Android枚举类中humanName字段的多语言支持问题

核心问题说明

枚举类在类加载阶段就会完成初始化,此时无法获取Context来访问本地化字符串资源,因此不能直接在枚举中存储硬编码字符串,必须改用字符串资源ID存储,等到需要显示时再通过Context获取对应语言的字符串。

步骤1:修改枚举类结构

将humanName的类型从String改为@StringRes Int,用来存储对应的字符串资源ID:

import android.content.Context
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes

enum class Theme(
    val theme: ThemeL,
    val name: String,
    @StringRes val humanNameResId: Int, // 替换原humanName为资源ID
    @DrawableRes val image: Int? = null,
) {
    THEME_1(
        theme = ThemeL.Theme1,
        name = "theme1",
        humanNameResId = R.string.theme1, // 对应strings.xml中的资源ID
        image = R.drawable.theme1
    ),
    THEME_2(
        theme = ThemeL.Theme2,
        name = "theme2",
        humanNameResId = R.string.theme2,
        image = R.drawable.theme1
    );

    // 添加方法,通过Context获取本地化字符串
    fun getHumanName(context: Context): String {
        return context.getString(humanNameResId)
    }
}

步骤2:使用本地化字符串

在需要显示humanName的地方,传入Context调用getHumanName()方法即可:

// Activity中使用示例
val themeName = Theme.THEME_1.getHumanName(this)
// Fragment中使用示例
val themeName = Theme.THEME_2.getHumanName(requireContext())

补充说明

  • 确保多语言strings.xml放置在正确目录:
    • 英文:res/values/strings.xml
    • 葡萄牙语:res/values-pt/strings.xml(巴西葡萄牙语用values-pt-rBR)
  • 该方式完全遵循Android多语言机制,系统会根据当前设备语言自动加载对应字符串资源。

内容的提问来源于stack exchange,提问作者Matheus Quintas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:10:00