not a constant in Enum

我与影子孤独终老i 提交于 2019-12-01 06:02:38

Add this code to your enum

private static final Map<String, FragmentName> map = new HashMap<>();
static {
    for (FragmentName en : values()) {
        map.put(en.text, en);
    }
}

public static FragmentName valueFor(String name) {
    return map.get(name);
}

Now instead of valueOf use valueFor

switch (Enums_String.FragmentName.valueFor(title))
//                                ^^^^^^^^

The valueOf

Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.

What you want do id get the enum by a member value for that you have write a function to do so like fromString below

 public enum FragmentName {

    FRAGMENT_NEWSFEED("NEWS FEED"),
    FRAGMENT_MESSAGES("MESSAGES"),
    FRAGMENT_EVENTS("EVENTS"),
    FRAGMENT_WHOISAROUDNME("WHOS AROUND");

    private final String text;

    private FragmentName(final String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }

    public static FragmentName fromString(String value) {
        for (FragmentName fname : values()) {
            if (fname.text.equals(value)) {
                return fname;
            }
        }
        return null;
    }
}

and replace your switch case like

    switch (FragmentName.fromString(title)) {
Christophe Schutz

Create a method like this :

public static FragmentName getFragmentNameByText(String text) {
    for (FragmentName fragment : values()) {
      if (fragment.text.equals(text)) {
         return fragment;
      }
    }
    return null;
}

and call this instead of valueOf().

You can change your function to compare the string values passed in:

public void changeTitle(String title) {
        if(title.equals(FRAGMENT_NEWSFEED.toString())) {
            System.out.println("1");
        } else if(title.equals(FRAGMENT_MESSAGES.toString())) {
            System.out.println("2");
        } else if(title.equals(FRAGMENT_EVENTS.toString())) {
            System.out.println("3");
        } else if(title.equals(FRAGMENT_WHOISAROUDNME.toString())) {
            System.out.println("4");
        } else {
            // throw an error
        }
    }

You can't operate an switch off of a function call, so you have to use an if-else block.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!