java – Android – 用@IntDef替换参数化枚举

如何使用@IntDef避免参数化枚举.

>我想保留一些与每个枚举/类型相关的静态细节(如关联的URl,相关的drawable等).

TYPE_ONE(R.string.res, Urls.URL1),

TYPE_TWO(R.string.res, Urls.URL2),

TYPE_THREE(R.string.res, Urls.URL3),

TYPE_FOUR(R.string.res, Urls.URL4),

TYPE_FIVE(R.string.res, Urls.URL5),

TYPE_SIX(R.string.res, Urls.URL6);

private final int mResId;
private final String mUrl;

Types(int titleResId, String url) {
  mResId = titleResId;
  mUrl = url;
}

public int getRes() {
   return mTitleResId;
}

public String getURL() {
   return mUrl;
}

什么是优化的方式来做到这一点?

最佳答案 我知道enums比整数消耗更多的资源,并且在Android上禁止它们,但是,在你所描述的情况下,我认为开销可以通过可读性的增益来弥补.

话虽这么说,使用@IntDef并将更多变量链接到它的一种方法可能是私有和静态声明所需资源的数组,并使用传递@IntDef的静态getter访问它们.

public class Constants {

    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;

    @IntDef(value={PAGE_ONE, PAGE_TWO, PAGE_THREE})
    public @interface PageType {}

    private static final SparseArray<String> PAGE_TITLES = new SparseArray<>();
    private static final SparseArray<Integer> PAGE_IMAGES = new SparseArray<>();
    static {
        PAGE_TITLES.put(PAGE_ONE, "PAGE_ONE");
        PAGE_IMAGES.put(PAGE_ONE, R.drawable.page_one);

        PAGE_TITLES.put(PAGE_TWO, "PAGE_TWO");
        PAGE_IMAGES.put(PAGE_TWO, R.drawable.page_two);

        PAGE_TITLES.put(PAGE_THREE, "PAGE_THREE");
        PAGE_IMAGES.put(PAGE_THREE, R.drawable.page_three);
    }

    public static int getPageDrawable(@PageType int pageNumber){
        return PAGE_IMAGES.get(pageNumber);
    }

    public static String getPageTitle(@PageType int pageNumber){
        return PAGE_TITLES.get(pageNumber);
    }

    private Constants(){}
}
点赞