Android:在枚举类中获取本地资源

huangapple go评论78阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月28日 04:33:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64093062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定