简体   繁体   English

在 static 初始化程序中是否有一种合理的方式来引用应用程序资源(R.string…)

[英]Is there a sensible way to refer to application resources (R.string…) in static initializers

Is there a sensible, clean way to refer to application resources from static initalizer code in my android classes.我的 android 类中的 static 初始化程序代码是否有一种明智、干净的方式来引用应用程序资源。

I would specifically like to define an enum which contains the values of some resource strings in its constants.我特别想定义一个枚举,它在其常量中包含一些资源字符串的值。

Here is some pseudo code for the enum这是枚举的一些伪代码

private enum MyEnum {
    Const1(getString(R.string.string1)),
    Const2(getString(R.string.string2)),
    Const3(getString(R.string.string3));

    private String strVal;

    MyEnum(String strVal){
        this.strVal = strVal;
    }
}

This question applies to any kind of static initialization.这个问题适用于任何类型的 static 初始化。

I don't think there is a direct way as context is required to load resources.我认为没有直接的方法,因为加载资源需要上下文。 However, what you could do is to provide a method in your enum to get required string once context is available.但是,您可以做的是在您的枚举中提供一个方法,以便在上下文可用时获取所需的字符串。 Something like就像是

private enum MyEnum {
    Const1(R.string.string1),
    Const2(R.string.string2),
    Const3(R.string.string3);

    private int resId;

    MyEnum(int resId){
        this.resId = resId;
    }

    public String resource(Context ctx) {
       return ctx.getString(resId);
    }
}

So you access it like所以你访问它就像

String val = Const3.resource(context);

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

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