该应用程序具有多语言 支持。但是我们在使用应用程序上下文刷新 Resources
时遇到了问题。
目前,我的 ViewModels
正在扩展 AndroidViewModel
,这样我们就可以访问 ViewModels
中的 Application 实例。但问题是 应用程序资源 不会在 Locale 更改后立即刷新。
因此,如果我更改语言环境并返回到我的 LoginActivity,则以下代码会给出不同的输出
String testText = getString(R.string.enter_email);
Timber.e("-- From Activity --");
Timber.e(testText);
Timber.e("-- From Application--");
testText = getApplication().getString(R.string.enter_email);
Timber.e(testText);
这段代码的Logcat输出如下
E/LoginActivity: -- From Activity --
E/LoginActivity: الرجاء إدخال البريد الإلكتروني
E/LoginActivity: -- From Application--
E/LoginActivity: Please enter your email
我正在使用以下代码 fragment 更新语言环境:
public static Context setLocale(Context context, String language) {
saveLocale(context, language);
CountryUtils.getDefaultCountryISO(context));
Locale locale = new Locale(language, CountryUtils.getDefaultCountryISO(context));
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
if (Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
context = context.createConfigurationContext(config);
} else {
config.locale = locale;
res.updateConfiguration(config, res.getDisplayMetrics());
}
return context;
}
我已按照此 blog 中提到的所有步骤进行操作还有这个answer .
我需要了解的是,为什么我们在 getApplication().getString()
和 this.getString()
之间有不同的资源?
最佳答案
在您的 Activity 中添加以下方法
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(PbContext.wrap(newBase, getmAppLanguage()))
}
请在下面找到扩展自定义上下文:
public class PbContext extends ContextWrapper {
public PbContext(Context base) {
super(base);
}
@SuppressWarnings("deprecation")
public static PbContext wrap(Context context, String language) {
Configuration config = context.getResources().getConfiguration();
if (language != null) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
config.setLayoutDirection(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
context = context.createConfigurationContext(config);
}
//Updating application
SampleApplication.setAppConfig(context);
return new PbContext(context);
}
@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config){
return config.locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config){
return config.getLocales().get(0);
}
@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale){
config.locale = locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale){
config.setLocale(locale);
}}
关于android - 更改语言环境时,未更新来自应用程序的 getResources。只有 Activity getResources 被正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57572262/