所以我正在尝试制作一个应用程序,您可以在其中将语言(在首选项 Activity 中)更改为系统默认语言或特定语言。每当您更改语言时,应用程序都会重新启动并选择新的语言环境。当第一个 Activity 开始时,它将必须使用的 Locale 保存到 Utils 类中的静态变量中。在每个 Activity 的 onCreate 方法中,我都会加载该语言环境。
现在,为了澄清,这里是 Utils 类的 Locale 部分:
private static Locale locale = null;
public static boolean isLocaleNull() {
return locale == null;
}
public static void setLocale(Locale locale) {
Utils.locale = locale;
}
public static void loadLocale(Context baseContext) {
if (locale == null) return;
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
baseContext.getResources().updateConfiguration(config, baseContext.getResources().getDisplayMetrics());
}
这是我的第一个 Activity 的 onCreate(只有语言环境部分):
if (!Utils.isLocaleNull()) {
String locale = PreferenceManager.getDefaultSharedPreferences(getBaseContext())
.getString(getResources().getString(R.string.prefsKeyLanguage), "default");
if (locale != null && !locale.equals("default"))
Utils.setLocale(new Locale(locale));
}
下面是我在所有 Activity 中加载语言环境的方式:
Utils.loadLocale(getBaseContext());
最后,在 loadLocale 中我们有 if (locale == null) return;
并且在语言环境加载器中我们有 if (... && !locale.equals("default"))
这意味着如果选择系统默认值,语言环境将为空,这意味着如果选择系统默认值,语言环境将不会更改。
一切都很完美!我的意思是,它按预期工作。但在某些情况下它会失败吗?这是不是一个好主意?我知道在某些情况下持有对实例的静态引用是个坏主意。这是某些情况之一吗?如果是,我该怎么办?
谢谢!
最佳答案
你是对的,这不是一个好主意,因为 Android 会在需要内存时尽快删除该静态变量(这种情况经常发生)。
您应该使用 SharedPreferences 设置和检索您的 Locale
。
要处理 SharedPreferences 中的 Object
,请使用 Gson
:
保存
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
检索
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
关于java - 保留对 Locale 实例的静态引用好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30558316/