Android语言切换方式实现,各应用需要准备两套String资源文件(中/英文)。
核心代码如下:
public static void setAppLanguage(Locale locale) {
String language = locale.getLanguage();
LogUtils.d(TAG, "setAppLanguage: locale = " + locale + ", language = " + language);
if (TextUtils.equals(language, Locale.CHINESE.toString())) {//中文
Log.d(TAG, "setAppLanguage(), persist.sys.locale = " + VALUE_LOCAL_ZH);
SystemProperties.set(KEY_LOCAL, VALUE_LOCAL_ZH);
InstrumentController.getInstance().sendLanguageChangeReq(1);
} else if (TextUtils.equals(language, Locale.ENGLISH.toString())) {//英语
Log.d(TAG, "setAppLanguage(), persist.sys.locale = " + VALUE_LOCAL_EN);
SystemProperties.set(KEY_LOCAL, VALUE_LOCAL_EN);
InstrumentController.getInstance().sendLanguageChangeReq(2);
}
try {
Log.d(TAG, "setAppLanguage() start " + locale.toString());
Object objIActMag;
Class clzAm = ActivityManager.class;
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
Class clzIActMag = Class.forName("android.app.IActivityManager");
Method getIamMethod = clzAm.getMethod("getService");
objIActMag = getIamMethod.invoke(am);
Method mtdIActMagGetConfiguration = clzIActMag.getDeclaredMethod("getConfiguration");
Configuration config = (Configuration) mtdIActMagGetConfiguration.invoke(objIActMag);
config.setLocale(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config.setLocales(new LocaleList(locale));
}
Method updatePersistentConfigurationMethod = clzIActMag.getMethod("updatePersistentConfiguration", Configuration.class);
updatePersistentConfigurationMethod.invoke(objIActMag, config);
Class[] clzParams = {Configuration.class};
Method mtdIActMagUpdateConfiguration = clzIActMag.getDeclaredMethod(
"updateConfiguration", clzParams);
mtdIActMagUpdateConfiguration.invoke(objIActMag, config);
Log.d(TAG, "setAppLanguage() end ");
} catch (Exception e) {
Log.d(TAG, "setAppLanguage() Exception " + e.getMessage());
e.printStackTrace();
}
}
- 需要监听主题切换,需要在AndroidManifest的activity标签增加android:configChanges =
“layoutDirection|locale”,重写onConfigurationChanged方法,在onConfigurationChanged中处理切换主题后的逻辑,重新加载资源;
优点 :当AndroidManifest.xml 里增加"layoutDirection|locale" ,可以避免页面闪烁问题,防止页面重走生命周期
<activity
android:name=".activity.MainActivity"
android:configChanges="layoutDirection|locale"
android:theme="@style/AppTheme">
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
String currentLanguage = newConfig.locale.getLanguage();
LogUtils.e(TAG, "onConfigurationChanged currentLanguage: " + currentLanguage);
}
//重新设置对应页面的字符串id