安卓原生切换语言,不需要重新启动APP,兼容7.0以下版本。
第一步 将要切换的语言保存在本地:我这里使用SharedPreferences将三种语言保存起来:en,zh,ru
第二步 我们写一个BaseActivity类,将它继承给每个activity:
@Override
protected void attachBaseContext(Context newBase) {
String language;
if(!TextUtils.isEmpty(SPUtils.getLanguage())) {
language = SPUtils.getLanguage();
} else {
Locale locale = Locale.getDefault();
language = locale.getLanguage();
}
Context context = LanguageUtil.attachBaseContext(newBase, language);
final Configuration configuration = context.getResources().getConfiguration();
final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context,
R.style.Theme_AppCompat_Empty) {
@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
if (overrideConfiguration != null) {
overrideConfiguration.setTo(configuration);
}
super.applyOverrideConfiguration(overrideConfiguration);
}
};
super.attachBaseContext(wrappedContext);
}
第三步 创建LanguageUtil 方法:
public class LanguageUtil {
public static void changeAppLanguage(Context context, String newLanguage) {
if (TextUtils.isEmpty(newLanguage)) {
return;
}
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
Locale locale = getLocaleByLanguage(newLanguage);
configuration.setLocale(locale);
DisplayMetrics dm = resources.getDisplayMetrics();
resources.updateConfiguration(configuration, dm);
}
public static Locale getLocaleByLanguage(String language) {
Locale locale = Locale.SIMPLIFIED_CHINESE;
if (language.equals(LanguageType.CHINESE.getLanguage())) {
locale = Locale.SIMPLIFIED_CHINESE;
} else if (language.equals(LanguageType.ENGLISH.getLanguage())) {
locale = Locale.ENGLISH;
} else if (language.equals(LanguageType.Russian.getLanguage())) {
locale = Locale.forLanguageTag(language);
}
return locale;
}
public static Context attachBaseContext(Context context, String language) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
} else {
return context;
}
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Resources resources = context.getResources();
Locale locale = LanguageUtil.getLocaleByLanguage(language);
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLocales(new LocaleList(locale));
return context.createConfigurationContext(configuration);
}
}
第四步:LanguageType当中定义的就是自定义的语言类型,可根据自己需求更改
public enum LanguageType {
CHINESE("zh"),
ENGLISH("en"),
Russian("ru");
private String language;
LanguageType(String language) {
this.language = language;
}
public String getLanguage() {
return language == null ? "" : language;
}
}
第五步 对于低版本手机小于7.0:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
String language = null;
if(!TextUtils.isEmpty(SPUtils.getLanguage())) {
language = SPUtils.getLanguage();
}
LanguageUtil.changeAppLanguage(MainApplication.getAppContext(), language);
}
本人第一次写,可能写的不太好,大神们请多多指教 。。。。。。