我在android应用程序中遇到本地化问题。
当我在api级别24和更高级别上对其进行测试时,用于更改语言的功能可以正常工作,但是当我在仿真器api级别23上进行语言更改时,它只会应用本地更改。我在许多论坛上都读到了这本书,并且我尝试了几乎所有提供的解决方案,但都行不通。
重要的是,关闭弹出菜单的动画listPreference比在Android Nougat上关闭动画有点怪异,因此它已经闻起来有些不规则。
重要说明是我在api级别23或棉花糖的物理设备上运行应用程序,问题仍然存在。
在以下各节中,我提供了一些对于这种情况很重要的代码,但另一方面,我省略了一些对于此类情况不是必需的文件,例如strings.xml和preferences.xml。因此,这里的主要重点是使更改应用程序语言的可能性成为可能。如果您有任何线索,我可能会问他与我们分享什么问题。
设置语言环境的助手类
package com.metropolitan.hangouter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.os.Build;
import java.util.Locale;
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
Configuration config = context.getResources().getConfiguration();
Locale sysLocale = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sysLocale = getSystemLocale(config);
} else {
sysLocale = getSystemLocaleLegacy(config);
}
if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
context = context.createConfigurationContext(config);
} else {
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
return new MyContextWrapper(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);
}
}
然后,在我的主要活动以及其他方法中,我将此称为对我们至关重要的方法。
override fun attachBaseContext(newBase: Context) {
preferences = PreferenceManager.getDefaultSharedPreferences(newBase)
vred = preferences.getString("languageKey", "no selection")!!
val locale = Locale(vred)
super.attachBaseContext(MyContextWrapper.wrap(newBase, locale.language))
}
此方法在SettingsActivity中也被调用,它具有相同的功能,并且会将本地配置附加到baseContext,当然,由于进行了更改并且我正在处理该事件,因此我需要刷新该活动。
因此,此方法在正确的位置和正确的时间调用。换句话说,每次onPreferenceChange时,我都会刷新活动。我的应用程序是用kotlin编写的,但是此MyContextWrapper类是在java中的。就是这样,如果有人需要更多信息,我将很高兴提供它。
发生这种情况的原因可能是:
从Android 7.0(API级别24)开始,Android为多语言用户提供了增强的支持,使他们可以在设置中选择多个语言环境。Android通过大大扩展支持的语言环境数量并更改系统解析资源的方式来提供此功能。
您可以在此处了解更多信息
如果您有名为xx_XX的资源,请尝试删除XX,这在较旧的版本上对我有用。否则,请指定完全限定的语言环境。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句