Android将String解析为StringDef

时间:2017-04-07 04:05:35

标签: android android-support-library

我在代码中声明了@StringDef

@StringDef({NotificationAction.DISPLAYED, NotificationAction.CONTENT_CLICKED,
    NotificationAction.ACTION_CLICKED, NotificationAction.DISMISSED})
@Retention(RetentionPolicy.SOURCE)
public @interface NotificationAction {
    String DISPLAYED = "Displayed";
    String CONTENT_CLICKED = "ContentClicked";
    String ACTION_CLICKED = "ActionClicked";
    String DISMISSED = "Dismissed";
}

如何将新字符串解析为NotificationAction而不单独将其与每个字符串进行比较?

在枚举中,我可以直接使用valueOf函数。我在这里找不到类似的东西。

1 个答案:

答案 0 :(得分:0)

除了实施它之外,您似乎无法做任何其他事情。我做的是以下内容。

public class Job {

    @IntDef(value = {
            Status.STOPPED,
            Status.STARTED,
            Status.NEW
    })
    @Retention(RetentionPolicy.SOURCE)
    @interface JobStatus {
    }

    public static class Status {
        public static final int STOPPED = 0;
        public static final int STARTED = 1;
        public static final int NEW = 2;

        @JobStatus
        static int getStatus(int status) {
            return status;
        }

        @JobStatus
        static int fromName(String name) {
            switch (name) {
                case "STOPPED":
                    return STOPPED;
                case "STARTED":
                    return STARTED;
                case "NEW":
                    return NEW;
                default:
                    return NEW;
            }
        }
    }
}

也许它可以帮到你。