【问题标题】:How to reload static methods on Android runtime如何在 Android 运行时重新加载静态方法
【发布时间】:2018-02-05 05:08:36
【问题描述】:

我目前正致力于在 Android 应用程序上动态更改语言环境。当用户的语言环境发生变化时,我将信息存储在 SharedPreferences 中,每个 Activity 在创建时都会引用语言环境信息。

但是,我的应用程序中的静态方法存在一些问题,尤其是在我的 Util 类中。我在我的静态方法中使用了特定于语言环境的字符串,但它们不会重新加载,因为它们已经在内存中。

似乎 android 在设备区域设置更改时重新加载所有类,因为更改设备语言/区域设置会带来所有适当的区域设置字符串。更改用户语言后如何手动执行此操作?

以下是在我的应用程序的 onConfigurationChanged 和我的活动的 attachBaseContext 中调用的代码。

Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());

config.setLocale(getLocale());
context = context.createConfigurationContext(config);

更新 这是我的代码中存在与静态方法相关的问题的一个示例。

public static String convertPassedDayFormat(Date date) {
    BaseApplication app = BaseApplication.get();
    int diffDay = diffDayFromCurrent(date);
    if (diffDay < 1) return app.getString(R.string.word_today);
    if (diffDay < 2) return app.getString(R.string.word_yesterday);
    if (diffDay < 4) return String.format(app.getString(R.string.word_day_passed), diffDay);
    return convertFormat(date, app.getString(R.string.format_print_day_year));
}

这部分代码不会返回适当的字符串。

【问题讨论】:

  • 您是否正在努力实现,您的应用支持多语言
  • @warlock 不一定是多语言的,但应用语言应该遵循用户的专用语言。因此,在登录/注册后,应用应该为用户显示适当的语言。
  • 顺便说一句,我改变locale的逻辑和支持多语言基本一样。
  • @confuoco 为什么不在应用程序中更改语言环境时重新启动应用程序。
  • 我其实不明白你的问题,能不能详细点

标签: java android static


【解决方案1】:

问题的问题在于您的静态方法 convertPassedDayFormat() 用于获取字符串资源,您使用的旧上下文可能不包含更新的配置(因为它是静态的)

您需要做的是,您应该将新的上下文作为参数传递给静态方法,而不是从 BaseApplication.get() 获取静态上下文方法,如下所示

public static String convertPassedDayFormat(Date date, Context app) {

    int diffDay = diffDayFromCurrent(date);
    if (diffDay < 1) return app.getString(R.string.word_today);
    if (diffDay < 2) return app.getString(R.string.word_yesterday);
    if (diffDay < 4) return String.format(app.getString(R.string.word_day_passed), diffDay);
    return convertFormat(date, app.getString(R.string.format_print_day_year));
}

【讨论】:

  • 我想这是正确的解决方案.. 但是有什么办法可以刷新我的 BaseApplication 吗?
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多