我可以使用Resources.getSystem()吗?

时间:2016-11-24 01:16:07

标签: android

我想从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()可能不安全 我担心它会返回nullinvalid Resources

我该如何解决这个问题?

0 个答案:

没有答案