1 public classAppLanguageUtils {2
3 public static HashMap mAllLanguages = new HashMap(8) {{4 put(Constants.ENGLISH, Locale.ENGLISH);5 put(Constants.CHINESE, Locale.SIMPLIFIED_CHINESE);6 put(Constants.SIMPLIFIED_CHINESE, Locale.SIMPLIFIED_CHINESE);7 put(Constants.TRADITIONAL_CHINESE, Locale.TRADITIONAL_CHINESE);8 put(Constants.FRANCE, Locale.FRANCE);9 put(Constants.GERMAN, Locale.GERMANY);10 put(Constants.HINDI, new Locale(Constants.HINDI, "IN"));11 put(Constants.ITALIAN, Locale.ITALY);12 }};13
14 @SuppressWarnings("deprecation")15 public static voidchangeAppLanguage(Context context, String newLanguage) {16 Resources resources =context.getResources();17 Configuration configuration =resources.getConfiguration();18
19 //app locale
20 Locale locale =getLocaleByLanguage(newLanguage);21
22 if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.JELLY_BEAN_MR1) {23 configuration.setLocale(locale);24 } else{25 configuration.locale =locale;26 }27
28 //updateConfiguration
29 DisplayMetrics dm =resources.getDisplayMetrics();30 resources.updateConfiguration(configuration, dm);31 }32
33
34 private staticboolean isSupportLanguage(String language) {35 returnmAllLanguages.containsKey(language);36 }37
38 public staticString getSupportLanguage(String language) {39 if(isSupportLanguage(language)) {40 returnlanguage;41 }42
43 if (null == language) {//为空则表示首次安装或未选择过语言,获取系统默认语言
44 Locale locale =Locale.getDefault();45 for(String key : mAllLanguages.keySet()) {46 if (TextUtils.equals(mAllLanguages.get(key).getLanguage(), locale.getLanguage())) {47 returnlocale.getLanguage();48 }49 }50 }51 returnConstants.ENGLISH;52 }53
54 /**55 * 获取指定语言的locale信息,如果指定语言不存在{@link #mAllLanguages},返回本机语言,如果本机语言不是语言集合中的一种{@link #mAllLanguages},返回英语56 *57 * @param language language58 * @return59 */
60 public staticLocale getLocaleByLanguage(String language) {61 if(isSupportLanguage(language)) {62 return mAllLanguages.get(language);63 } else{64 Locale locale =Locale.getDefault();65 for(String key : mAllLanguages.keySet()) {66 if (TextUtils.equals(mAllLanguages.get(key).getLanguage(), locale.getLanguage())) {67 returnlocale;68 }69 }70 }71 returnLocale.ENGLISH;72 }73
74
75 public staticContext attachBaseContext(Context context, String language) {76 if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.N) {77 returnupdateResources(context, language);78 } else{79 returncontext;80 }81 }82
83
84 @TargetApi(Build.VERSION_CODES.N)85 private staticContext updateResources(Context context, String language) {86 Resources resources =context.getResources();87 Locale locale =AppLanguageUtils.getLocaleByLanguage(language);88
89 Configuration configuration =resources.getConfiguration();90 configuration.setLocale(locale);91 configuration.setLocales(newLocaleList(locale));92 returncontext.createConfigurationContext(configuration);93 }94
95 }