我想从static final String[]
初始化string.xml
变量
所以我找到了解决方案Resources.getSystem()
但是,我很担心使用它。
这是我使用之前的代码。
public enum Type {
STUDENT, TEACHER, PARENT, GRADUATE, OTHERS;
public static final int[] typeNamesRes = new int[] {
R.string.student,
R.string.teacher,
R.string.parent,
R.string.graduate,
R.string.others;
};
public static final String[] typeNames= new String[typeNamesRes.length];
public static init(Context context) {
for (int i=0; i<typeNamesRes.length; i++) {
typeNames[i] = context.getString(typeNamesRes[i]);
}
}
@Override
public String toString() {
return typeNames[ordinal()];
}
}
但是,此代码必须调用init
方法
我觉得这不是好办法
因为没有调用init
方法(错误地)
所以我使用Resources.getSystem()
。
public enum Type {
STUDENT, TEACHER, PARENT, GRADUATE, OTHERS;
public static final String[] typeNames = new String[] {
Resources.getSystem().getString(R.string.student),
Resources.getSystem().getString(R.string.teacher),
Resources.getSystem().getString(R.string.parent),
Resources.getSystem().getString(R.string.graduate),
Resources.getSystem().getString(R.string.others);
};
@Override
public String toString() {
return typeNames[ordinal()];
}
}
但是,我认为Resources.getSystem()
可能不安全
我担心它会返回null
或invalid Resources
。
我该如何解决这个问题?