英文:
Android: get local resources in enumerate class
问题
我正在编写一个使用Java代码的Android应用程序。该应用程序可以支持英语和意大利语。在应用程序内部,有一个微调器(spinner),它从一个枚举类中获取其值,如下所示:
public enum ElementTypesEnum {
MEET("Meet"),
CEREAL("Cereal"),
FISH("Fish"),
OTHER("Other");
private String elementType;
ElementTypesEnum(String elementType) {
this.elementType = elementType;
}
public String getElementType() {
return elementType;
}
}
我想要使用本地字符串资源文件(R.string.value_1)中包含的值来初始化枚举的值。在这个类中,我没有资源文件的实例,因为我没有Context的实例。我应该如何做到这一点?非常感谢,Marco
英文:
I'm writing an android application with java code. The app can support english and italian. Inside the app, there is a spinner that take its values from an enumerate class, the following:
public enum ElementTypesEnum {
MEET("Meet"),
CEREAL("Cereal"),
FISH("Fish"),
OTHER("Other");
private String elementType;
ElementTypesEnum(String elementType) {
this.elementType = elementType;
}
public String getElementType() {
return elementType;
}
}
I want to initialize the values of the enumerate with the values contained in my local string resource file (R.string.value_1). In this class I don't have an instance of the resource file, since I don't have an instance of Context. How can I do this? Thank you in advance, Marco
答案1
得分: 0
使用资源ID,然后在填充时使用您的spinner的上下文来获取字符串。
public enum ElementTypesEnum {
MEAT(R.string.meat),
CEREAL(R.string.cereal),
FISH(R.string.fish),
OTHER(R.string.other);
@StringRes
private int elementType;
ElementTypesEnum(@StringRes int elementType) {
this.elementType = elementType;
}
public int getElementType() {
return elementType;
}
}
英文:
Use the resource ID then fetch the strings with your spinner's Context when you populate it.
public enum ElementTypesEnum {
MEAT(R.string.meat),
CEREAL(R.string.cereal),
FISH(R.string.fish),
OTHER(R.string.other);
@StringRes
private int elementType;
ElementTypesEnum(@StringRes int elementType) {
this.elementType = elementType;
}
public int getElementType() {
return elementType;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论