新年好啊,一些面向国际化的应用需要支持多语言,客户说要是增加一个语言切换的功能最好不过了,今天,它来了。
先看效果图
思路
首先开始做一个功能前脑中需要考虑到的问题有这么几点:保存语言状态,全局设置,语言缩写,进入APP时的初始化,切换后的生命周期
资源文件必不可少,注意资源文件名的命名方式,如果不一致会导致切换失败.
这里列举几个常用的语言文件名后缀
英文(en)
,繁体(tw)
,日语(ja)
,西班牙语(es)
,中文(ch)
开始K代码,注意这里使用了两种语言:kotlin
,java
1.语言状态保存
import android.content.Context;
import android.content.SharedPreferences;
/**
* 保存语言状态
* by:Allyn
*/
public class SpUtil {
public static final String LANGUAGE = "language";
private static final String SP_NAME = "poemTripSpref";
private static SpUtil spUtil;
private static SharedPreferences hmSpref;
private static SharedPreferences.Editor editor;
private SpUtil(Context context) {
hmSpref = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = hmSpref.edit();
}
public static SpUtil getInstance(Context context) {
if (spUtil == null) {
synchronized (SpUtil.class) {
if (spUtil == null) {
spUtil = new SpUtil(context);
}
}
}
return spUtil;
}
public void putString(String key, String value) {
editor.putString(key, value);
editor.commit();
}
public String getString(String key) {
return hmSpref.getString(key,"");
}
}
2.支持的语言类型
/**
* 语言切换类型
* by:Allyn
*/
public enum LanguageType {
CHINESE("ch"),
ENGLISH("en"),
THAILAND("tw"),
SPAIN("es"),
JAPAN("ja");
private String language;
LanguageType(String language) {
this.language = language;
}
public String getLanguage() {
return language == null ? "" : language;
}
}
3.语言切换处理
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 androidx.annotation.RequiresApi;
import java.util.Locale;
/**
* 语言切换处理
* by:Allyn
*/
public class LanguageUtil {
private static final String TAG = "LanguageUtil";
/**切换语言关键类
* @param context
* @param newLanguage
*/
@SuppressWarnings("deprecation")
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);
// updateConfiguration
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.THAILAND.getLanguage())) {
locale = Locale.TRADITIONAL_CHINESE;
} else if (language.equals(LanguageType.JAPAN.getLanguage())) {
locale = Locale.JAPAN;
} else if (language.equals(LanguageType.SPAIN.getLanguage())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
locale = Locale.forLanguageTag(language);
}
}
Log.d(TAG, "getLocaleByLanguage: " + locale.getDisplayName());
return locale;
}
//判断系统版本,给出不同处理方式
public static Context attachBaseContext(Context context, String language) {
Log.d(TAG, "attachBaseContext: " + Build.VERSION.SDK_INT);
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);
}
}
4.初始化处理
在Application类中获取语言状态进行初始化加载
/**
* author : Allyn
* e-mail : 1839565349@qq.com
* date : 2019/4/239:59
* desc :
*/
class App : Application() {
companion object {
var instance: Context by Delegates.notNull()
var template_type_id = -1
var device_name = ""
}
override fun onCreate() {
super.onCreate()
instance = applicationContext
// 注册Activity生命周期回调监听
// registerActivityLifecycleCallbacks(ActivityManager.getInstance())
/**
* 对于7.0以下,需要在Application创建的时候进行语言切换
*/
val language = SpUtil.getInstance(this).getString(SpUtil.LANGUAGE)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
LanguageUtil.changeAppLanguage(instance, language)
}
}
}
在所有Activity的父类中重写attachBaseContext方法,切换完成重新跳转界面后执行
/**
* 此方法先于 onCreate()方法执行
* @param newBase
*/
override fun attachBaseContext(newBase: Context) {
//获取我们存储的语言环境 比如 "en","zh",等等
val language = SpUtil.getInstance(App.instance).getString(SpUtil.LANGUAGE)
/**
* attach对应语言环境下的context
*/
super.attachBaseContext(LanguageUtil.attachBaseContext(newBase, language))
}
5.执行语言切换方法
/**
* 如果是7.0以下,我们需要调用changeAppLanguage方法,
* 如果是7.0及以上系统,直接把我们想要切换的语言类型保存在SharedPreferences中即可
* 然后重新启动MainActivity
*
* @param language
*/
public void changeLanguage(String language) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
LanguageUtil.changeAppLanguage(App.Companion.getInstance(), language);
}
SpUtil.getInstance(getActivity()).putString(SpUtil.LANGUAGE, language);
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
apply
changeLanguage(LanguageType.THAILAND.language)
// changeLanguage(LanguageType.SPAIN.language)
到这里这个功能就完成了,