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

如何在RecyclerView中强制使用默认英文字符串资源控制导航?

故障根因

当前崩溃的核心原因是导航ID的匹配逻辑依赖了本地化字符串:切换到阿拉伯语后,context.resources.getString(item.subSectionSrcID) 返回的是阿拉伯语文本,用阿拉伯语字符串去匹配英文命名的navGraph ID自然无法匹配,getIdentifier 会返回0,调用navigate时就会因为传入非法ID抛出异常。

修复方案

核心逻辑是匹配ID时强制读取英文Locale下的字符串,展示文本仍保留当前Locale的多语言效果,修改步骤如下:

  1. 先添加一个获取指定Locale字符串的工具方法:
fun getStringForLocale(context: Context, stringResId: Int, targetLocale: Locale = Locale.ENGLISH): String {
    val config = Configuration(context.resources.configuration)
    config.setLocale(targetLocale)
    return context.createConfigurationContext(config).resources.getString(stringResId)
}
  1. 修改原有Adapter中的点击逻辑:
override fun onBindViewHolder(holder: SubSectionListHolder, position: Int) {
    val item = dataset[position]
    // 展示文本保持当前系统Locale的多语言效果,不影响用户观感
    holder.subSectionView.text = context.resources.getString(item.subSectionSrcID)
    holder.subSectionView.setOnClickListener {
        // 匹配导航ID时强制用英文Locale的字符串
        val enNavName = getStringForLocale(context, item.subSectionSrcID).replace("\\s".toRegex(), "")
        val stringConvertToId = it.resources.getIdentifier(
            enNavName,
            "id",
            context.packageName
        )
        // 增加ID合法性判断,进一步避免崩溃
        if (stringConvertToId != 0) {
            it.findNavController().navigate(stringConvertToId)
        }
    }
}
优化建议
  • 你可以直接在列表的数据集类中新增navResId字段,提前存储对应导航ID,不需要运行时动态匹配字符串,性能更高,也完全不受多语言逻辑影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:54:05