package com.driver.igotrip.utils;
|
|
import android.content.Context;
|
import android.content.res.Configuration;
|
import android.os.Build;
|
import android.os.LocaleList;
|
import android.text.TextUtils;
|
import android.util.Log;
|
|
import java.util.Locale;
|
|
public class LanguageManager {
|
|
/**
|
* 为 Application/Activity 提供经过语言配置的 Context
|
* 必须在 attachBaseContext 中调用
|
*/
|
public static Context wrapContext(Context context) {
|
String language = LanguageSP.getLanguage(context);
|
Log.e("语言: ", language);
|
// 否则根据保存的语言配置 Context
|
return updateContextLocale(context, language);
|
}
|
|
/**
|
* 更新 Context 的语言配置(适配全版本)
|
*/
|
private static Context updateContextLocale(Context context, String language) {
|
Locale targetLocale = getLocaleFromLanguage(language);
|
Configuration configuration = context.getResources().getConfiguration();
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
// 7.0+ 用 LocaleList 配置
|
configuration.setLocales(new LocaleList(targetLocale));
|
// 创建新的 Context(必须用 createConfigurationContext,否则不生效)
|
return context.createConfigurationContext(configuration);
|
} else {
|
// 7.0 以下直接设置 locale
|
configuration.locale = targetLocale;
|
// 更新资源配置
|
context.getResources().updateConfiguration(
|
configuration,
|
context.getResources().getDisplayMetrics()
|
);
|
return context;
|
}
|
}
|
|
/**
|
* 将语言字符串(如 "zh-CN")转换为 Locale 对象
|
*/
|
private static Locale getLocaleFromLanguage(String language) {
|
if (TextUtils.isEmpty(language)) {
|
return Locale.FRENCH;
|
}
|
String[] parts = language.split("-");
|
if (parts.length == 1) {
|
return new Locale(parts[0]); // 如 Const.Language.ENGLISH -> Locale(Const.Language.ENGLISH)
|
} else {
|
return new Locale(parts[0], parts[1]); // 如 "zh-CN" -> Locale("zh", "CN")
|
}
|
}
|
}
|