Android APP内切换语言无感重启到当前界面
获取系统设置的语言
Locale.getDefault().getLanguage();
获取某个语言环境下的字符串
fun getLocalizedString(context: Context, lanCode: String, @StringRes resId: Int): String {var code = lanCodeif (code == FOLLOW_SYSTEM) {// 默认使用系统语言code = Locale.getDefault().languageif (code.isNullOrEmpty()) code = "en"}val config = Configuration(context.resources.configuration)config.setLocale(Locale.forLanguageTag(code))val localizedContext = context.createConfigurationContext(config)return localizedContext.resources.getString(resId)
}
无感重启所有Activity
fun restartAllActivity() {for (activity in listActivity) {val intent = activity.intentintent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)activity.finish()activity.overridePendingTransition(0, 0)activity.startActivity(intent)activity.overridePendingTransition(0, 0)}
}
APP内设置语言
重启所有Activity后,在BaseActivity的attachBaseContext中设置语言,注意写法
public static Context getChangeLangContext(Context context) {Configuration configuration = new Configuration();configuration.setLocale(new Locale(getLanguageCode(context)));context.getResources().updateConfiguration(configuration, null);return context;}
public abstract class BaseActivity{@Overrideprotected void attachBaseContext(Context newBase) {super.attachBaseContext(LanguageUtils.getChangeLangContext(newBase));}
}
注意
如果跟随系统菜单不灵了,获取到的不是系统设置的语言,可能是设置语言的代码导致的问题,卸载APP重装就不会有这问题了。