简体   繁体   English

有没有办法从 strings.xml 定义静态字符串数组

[英]Is there a way to define a static String array from strings.xml

I want to declare a static string array using an array in strings.xml .我想使用strings.xml的数组声明一个静态字符串数组。

private static final String[] tip_types = getResources().getStringArray(R.array.tip_types_array);

but you cannot use getResources() 'in a static context'.但是你不能在静态上下文中使用getResources() Is there a way to do this or must I not use a static variable?有没有办法做到这一点,或者我必须不使用静态变量?

Obviously显然

private final String[] tip_types = getResources().getStringArray(R.array.tip_types_array);

works, but then the declared array is not static.有效,但是声明的数组不是静态的。

To fetch resources (including strings) you always need a context.要获取资源(包括字符串),您始终需要一个上下文。 When you create a static field, even within an Activity, you cannot access the instance fields and therefore there's no context available.当您创建静态字段时,即使在 Activity 中,您也无法访问实例字段,因此没有可用的上下文。

You have two options to solve the problem:您有两种选择来解决问题:

Method 1方法一
You can create an Application class that stores the application context in a static field upon creation and get your string array using the application context.您可以创建一个 Application 类,在创建时将应用程序上下文存储在静态字段中,并使用应用程序上下文获取字符串数组。

private final static String[] tip_types = YourApplicationClass.getAppContext().getResources().getStringArray(R.array.tip_types_array);

Method 2方法二
You can create a getter for your static variable where you pass a context.您可以为传递上下文的静态变量创建一个 getter。 Like a singleton you check if the array is already resolved, and return it right away or fetch is using the supplied context.像单例一样,您检查数组是否已经解析,并立即返回它或 fetch 使用提供的上下文。 This has the advantage of lazy initialisation, the array is only created when it's actually needed.这具有延迟初始化的优点,仅在实际需要时才创建数组。

private static String[] tip_types;

private static String[] getTipTypes(Context context) {
    if(tip_types == null) {
        tip_types = context.getResources().getStringArray(R.array.tip_types_array);
    }
    return tip_types;
}

The first one, you need declare a NfcApplication custom class which extend from Application class:第一个,您需要声明一个从 Application 类扩展的 NfcApplication 自定义类:

public final class NfcApplication extends Application {

    private static NfcApplication sApplication;

    public static NfcApplication getInstance() {
        return sApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sApplication = this;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

        sApplication = null;
    }
}

The second one, then you can call the context by this way第二个,那么就可以这样调用上下文了

private static final String[] ARRAY_LIST = NfcApplication.getInstance().getResources().getStringArray(R.array.label_unit_array_str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM