从Android文档:
默认情况下,Android使用设备的区域设置来选择适当的语言相关资源。大多数时候这种行为足以
常见的
应用。
在内部更改语言是一个例外。
首先,请阅读
this documentation
承认设计的缺陷。
总而言之,我想提两件事:
-
updateConfiguration
已弃用,因此我们需要另一个版本来支持向后兼容。
-
我们需要超越
attachBaseContext
以反映变化的每一项活动。
实现方法如下:
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
configuration.setLayoutDirection(locale);
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
为了支持向后兼容,请在更改语言之前检查版本:
public static Context setLocale(Context context, String language) {
// You can save SharedPreference here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
在你
LoginActivity
,更改区域设置后,不必重新创建活动,您可以获取资源,然后更改
TextView
手动。
Context context = LocaleUtils.setLocale(this, lang);
Resources resources = context.getResources();
yourFirstTextView.setText(resources.getString(R.string.your_first_text_res)
// ... yourSecondTextView....
在每个活动中,要反映更改,请添加此函数:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleUtils.onAttach(newBase));
}
顺便说一句,有个bug,您不能更改的标题语言
Toolbar
. 在你
onCreate()
,手动调用此函数,
setTitle("your Title")
我知道这些问题很难看,解决方法也有点老套。但让我们试试看。如果这对你有帮助,请告诉我。:)
完整的源代码可以在这里找到:
https://github.com/gunhansancar/ChangeLanguageExample/blob/master/app/src/main/java/com/gunhansancar/changelanguageexample/helper/LocaleHelper.java
关于greate文章:
https://gunhansancar.com/change-language-programmatically-in-android/