有没有一种合理的方式来引用应用程序资源(R.string ...)的静态初始化 [英] Is there a sensible way to refer to application resources (R.string...) in static initializers

查看:90
本文介绍了有没有一种合理的方式来引用应用程序资源(R.string ...)的静态初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个合理的,干净的方式来引用应用程序资源从静态initalizer code。在我的Andr​​oid类。

Is there a sensible, clean way to refer to application resources from static initalizer code in my android classes.

我特别喜欢定义包含在其常量的资源字符串的值的枚举。

I would specifically like to define an enum which contains the values of some resource strings in its constants.

下面是一些伪code的枚举

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.

推荐答案

我不认为这是因为需要上下文来加载资源的直接途径。但是,你可以做的是提供您的枚举的方法来获得所需的字符串,一旦环境可用。类似于

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);

这篇关于有没有一种合理的方式来引用应用程序资源(R.string ...)的静态初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆