java - 从android资源中获取静态内容的更好方法?

标签 java android

我编写了一个名为 DateUtils 的类,我尝试像这样在静态字段中获取资源

    public class DateUtils{
    private static String value;

    public static string getValue(Context context){
            if (value== null) {
            value= context.getResources().getString(R.string.my_value);
            }
            return value; }
    }

但我找到了答案 How can I get a resource content from a static context?他们在其中创建了一个应用程序类并获取该应用程序类的引用来为静态字段赋值。

In this way the downside is that there is no guarantee that the non-static onCreate() will have been called before some static initialization code tries to fetch your Context object. That means your calling code will need to be ready to deal with null values which sort of defeats the whole point of this question Reference Static way to get 'Context' on Android?

我的问题是哪种方法是初始化静态字段的更好方法?

最佳答案

My question is which one is better approach to initialize static field?

都不是。去掉static字段。

您的应用程序需要处理用户在进程仍在运行时更改语言的情况。您需要在更合适的点检索此字符串资源,以便当您进行配置更改时,您可以开始使用正确的字符串。就目前情况而言,通过您的实现(无论您如何填充 static 字段),您都永远不会更改此字符串的语言,因此在某些情况下该字符串将是错误的。

如果答案是“这个字符串永远不会被翻译”,则删除该字符串资源并将该字符串作为 final static 字段放入 Java 代码中。

关于java - 从android资源中获取静态内容的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491724/

相关文章:

android - Android 4.3 更新后目标未知

android - 我的 ArrayList 中的唯一值

java - 在 Java 中执行 shell 命令行

java - 接收 SSLHandshakeException : handshake_failure despite my client ignoring all certs

java - 在 Windows 上将 Ctags 与 Gvim 结合使用

java - 当在 ArrayList 中找到字符串时 ArrayList.contains() 等于 false

android - 更改已弃用的 TabActivity

java - 解析文本文件中的输入

Android 服务到 Activity 通信性能

android - Logcat 不会出现