package cn.sinata.xldutils.utils; import static android.content.ContentValues.TAG; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.LocaleList; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import java.util.Locale; public class LanguageUtil { public static Context attachBaseContext(Context context, String language, String country) { Log.d(TAG, "attachBaseContext: "+ Build.VERSION.SDK_INT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return updateResources(context, language,country); } else { return context; } } @TargetApi(Build.VERSION_CODES.N) private static Context updateResources(Context context, String language, String country) { Resources resources = context.getResources(); Locale locale = new Locale(language); Configuration configuration = resources.getConfiguration(); configuration.setLocale(locale); configuration.setLocales(new LocaleList(locale)); return context.createConfigurationContext(configuration); } /** * @param context * @param newLanguage 想要切换的语言类型 比如 "en" ,"zh" */ @SuppressWarnings("deprecation") public static void changeAppLanguage(Context context, String newLanguage, String country) { if (TextUtils.isEmpty(newLanguage)) { return; } Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); //获取想要切换的语言类型 Locale locale = new Locale(newLanguage,country); configuration.setLocale(locale); // updateConfiguration DisplayMetrics dm = resources.getDisplayMetrics(); resources.updateConfiguration(configuration, dm); } /** * 如果是7.0以下,我们需要调用changeAppLanguage方法, * 如果是7.0及以上系统,直接把我们想要切换的语言类型保存在SharedPreferences中,然后重新启动MainActivity即可 */ public static void setLanguage(String language,String country,Context appContext){ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { changeAppLanguage(appContext, language,country); } SPUtils.Companion.instance().put("language",language); SPUtils.Companion.instance().put("country",country); } public static void set(boolean isEnglish, Context context) { Configuration configuration = context.getResources().getConfiguration(); DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); if (isEnglish) { //设置英文 configuration.locale = Locale.ENGLISH; } else { //设置中文 configuration.locale = Locale.SIMPLIFIED_CHINESE; } //更新配置 context.getResources().updateConfiguration(configuration, displayMetrics); } }