是否有一种明智,干净的方式来引用我的android类中的静态initalizer代码中的应用程序资源.
我特别想定义一个枚举,它包含常量中某些资源字符串的值.
这是枚举的一些伪代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
此问题适用于任何类型的静态初始化.
Ale*_*man 11
我不认为有一种直接的方式,因为加载资源需要上下文.但是,您可以做的是在枚举中提供一个方法,以便在上下文可用时获取所需的字符串.就像是
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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以你就像访问它一样
String val = Const3.resource(context);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1949 次 |
| 最近记录: |