本文介绍了Android-用@IntDef替换参数化的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i avoid parameterized enum with @IntDef.


  1. 我想保持静态与每个枚举/类型相关的详细信息(如相关的URl,相关的drawable等)。

  1. I want keep some static details associated with each enum/type (like associated URl , associated drawable etc.).

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


优化方式是什么去做这个?

Whats the optimized way to do this?

推荐答案

我知道 enum 消耗的资源比整数多,并且Android上禁止使用它们,但是,在您所描述的情况下,我认为开销由可读性得到补偿。

I know that enums consume much more resources than integers and there is a ban on them on Android, however, in situations like the one you're describing I think the overhead is compensated by the gain in readability.

话虽如此,一种使用 @IntDef 并将其链接到更多变量的方法可能是私下使用静态声明所需资源的数组,并通过传递 @IntDef 的静态getter访问它们。

That being said, one way to use @IntDef and link more variables to it could be to have privately and statically declare arrays of whatever resource you need, and access them with static getters passing the @IntDef.

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(){}
}

这篇关于Android-用@IntDef替换参数化的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:27