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

Android仅为特定UI元素切换Locale时遇资源找不到异常求助

问题解决:特定UI元素切换Locale时的ResourcesNotFoundException

核心问题分析

  1. Locale构造不完整:代码拆分了语言和国家码,但仅用语言码创建Locale,无法匹配Android标准资源文件夹(如values-ko-rKR),导致找不到对应语言资源。
  2. 空值未处理:getResourcesByLocale可能返回null,直接调用getString触发崩溃。
  3. Configuration修改不规范:直接复用原Context的Configuration副本存在兼容性风险,需创建独立实例避免影响全局配置。

修正后的代码

1. 修复getResourcesByLocale方法

public Resources getResourcesByLocale(Context context, String languageCode) {
    if (context == null || TextUtils.isEmpty(languageCode)) {
        Log.d(TAG, "Invalid context or language code");
        return null;
    }

    String[] languageCountry = languageCode.split("-");
    if (languageCountry.length < 2) {
        Log.d(TAG, "Language code format error, should be like 'en-US'");
        return null;
    }

    String language = languageCountry[0];
    String country = languageCountry[1];
    Locale targetLocale = new Locale(language, country);

    // 创建独立的Configuration副本
    Configuration config = new Configuration(context.getResources().getConfiguration());
    config.setLocale(targetLocale);

    // 兼容Android 7.0+多Locale设置
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocales(new LocaleList(targetLocale));
    }

    try {
        return context.createConfigurationContext(config).getResources();
    } catch (Exception e) {
        Log.e(TAG, "Failed to create resources for locale: " + targetLocale, e);
        return null;
    }
}

2. 完善updateTextByLocale方法(增加空值与异常校验)

public void updateTextByLocale(Context context, String languageCode, TextView tv, int resId) {
    if (tv == null || context == null) {
        Log.d(TAG, "Invalid TextView or Context");
        return;
    }

    Resources localeResources = getResourcesByLocale(context, languageCode);
    if (localeResources != null) {
        try {
            tv.setText(localeResources.getString(resId));
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "String resource not found for ID: " + resId, e);
            //  fallback到默认Locale文本
            tv.setText(context.getResources().getString(resId));
        }
    } else {
        // 获取不到对应Locale资源时,使用默认文本
        tv.setText(context.getResources().getString(resId));
    }
}

额外验证步骤

  • 检查资源文件夹命名:确保语言资源文件夹符合Android规范:
    • 英语(US):res/values-en-rUS/strings.xml
    • 韩语(KR):res/values-ko-rKR/strings.xml
  • 确认languageCode格式:调用时传入的语言码必须是"en-US"、"ko-KR"这类语言-国家格式的字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:15:33