android知识收集

Android国际化(多语言)

2018-11-14  本文已影响0人  YuanchaoLi

资源匹配

工程内初始化设置

Application

Activity

应用内变更语言

  1. 用户语言设置后,本地sp保存的语言
  2. 应用内语言变更
public static Context checkLanguage(Context context) {
    // index:本地保存的语言类型:0英语,1中文简体,2中文繁体
    int index = DataRepository.getInstence().getSpValue(SPConstant.SP_LANGUAGE, SPConstant.KEY_LANGUAGE_INDEX, -1);
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    DisplayMetrics displayMetrics = resources.getDisplayMetrics();
    Locale locale;
    if (index == LanguageConstant.ENGLISH) {
        locale = Locale.ENGLISH;
    } else if (index == LanguageConstant.SIMPLIFIED_CHINESE) {
        locale = Locale.SIMPLIFIED_CHINESE;
    } else if (index == LanguageConstant.CHINESE_TW) {
        locale = Locale.TRADITIONAL_CHINESE;
    } else {
        // 获取系统默认语言,版本兼容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = LocaleList.getDefault().get(0);
        } else {
            locale = Locale.getDefault();
        }
    }
    // 设置语言,版本做兼容
    // 这个updateConfiguration方法已废弃,官方建议用createConfigurationContext。但是仍然可以用
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        configuration.setLocale(locale);
        context = context.createConfigurationContext(configuration);
    } else {
        configuration.locale = locale;
        resources.updateConfiguration(configuration, displayMetrics);
    }
    return context;
}
  1. 对应的Activity调recreate()方法

系统适配、兼容

以上应用内设置语言涉及到部分需要兼容的Api

// 获取系统当前语言
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = LocaleList.getDefault().get(0);
} else {
    locale = Locale.getDefault();
}
// 设置应用语言;更新配置信息
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    configuration.setLocale(locale);
    context = context.createConfigurationContext(configuration);
} else {
    configuration.locale = locale;
    resources.updateConfiguration(configuration, displayMetrics);
}

Android7.0系统

自Android7.0系统起,由LocaleList管理语言

Android7.0及以上的系统,语言需要植入到Context中

@Override 
protected void attachBaseContext(Context base) {
    super.attachBaseContext(checkLanguage(base));
} 

Android8.0系统

上一篇 下一篇

猜你喜欢

热点阅读