Demo效果图
Demo中主要设置了三种情况:跟随系统、简体中文和英文具体步骤如下:
一、在资源文件中建立多语言环境的资源文件,具体步骤可参考以下链接:
https://blog.csdn.net/MakerCloud/article/details/83146600
二、新建工具类MultiLanguageUtils.java,
public class MultiLanguageUtils {
/**
* Todo 更新应用语言
* @param context
* @param locale
*/
public static void setAppLanguage(Context context, Locale locale) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
resources.updateConfiguration(configuration, metrics);
}
/**
* 判断系统中和app中的多语言信息是否相同
*/
public static boolean isSameWithSystem(Context context) {
String mTmpLanguage = null;
String appLanguage = (String) SPUtils.get(context, Constant.SP.LANGUAGE, "");
String systemLanguage = Locale.getDefault().getLanguage();
if("en".equals(systemLanguage)){
mTmpLanguage = "English";
} else if("zh".equals(systemLanguage)){
mTmpLanguage = "简体中文";
}
if (mTmpLanguage.equals(appLanguage)) {
return true;
} else {
return false;
}
}
/**
* 保存多语言信息到sp中
*/
public static void saveLanguageSetting(Context context, Locale locale) {
SPUtils.put(context, Constant.SP.LANGUAGE,locale.getLanguage());
SPUtils.put(context, Constant.SP.COUNTRY,locale.getCountry());
}
/**
* 获取应用语言
*/
public static Locale getAppLocale(Context context){
Locale local;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
local =context.getResources().getConfiguration().getLocales().get(0);
} else {
local =context.getResources().getConfiguration().locale;
}
return local;
}
/**
* 获取系统语言
*/
public static LocaleListCompat getSystemLanguage1(){
Configuration configuration = Resources.getSystem().getConfiguration();
LocaleListCompat locales = ConfigurationCompat.getLocales(configuration);
return locales;
}
public static Locale getSystemLanguage(){
Locale mLocale = null;
String systemLanguage = Locale.getDefault().getLanguage();
if("en".equals(systemLanguage)){
mLocale = Locale.ENGLISH;
} else if("zh".equals(systemLanguage)){
mLocale = Locale.SIMPLIFIED_CHINESE;
}
return mLocale;
}
//注册Activity生命周期监听回调,此部分一定加上,因为有些版本不加的话多语言切换不回来
//registerActivityLifecycleCallbacks(callbacks);
public static Application.ActivityLifecycleCallbacks callbacks = new Applicatio