android开发Enum (枚举)的完美替代 —— @IntDef的使用

     官方文档说明,安卓开发应避免使用Enum(枚举类),因为相比于静态常量Enum会花费两倍以上的内存。参 http://developer.android.com/training/articles/memory.html#Overhead

    那么如果需要使用Enum应该怎么做呢?

    https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/

public class MainActivity extends Activity {
  
    //先定义 常量
    public static final int SUNDAY = 0;
    public static final int MONDAY = 1;
    public static final int TUESDAY = 2;
    public static final int WEDNESDAY = 3;
    public static final int THURSDAY = 4;
    public static final int FRIDAY = 5;
    public static final int SATURDAY = 6;
  
    //用 @IntDef "包住" 常量;
    // @Retention 定义策略
    // 声明构造器
    @IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
    @Retention(RetentionPolicy.SOURCE)
    public @interface WeekDays {}
  
    @WeekDays int currentDay = SUNDAY;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setCurrentDay(WEDNESDAY);
  
        //声明变量
        @WeekDays int today = getCurrentDay();
  
        switch (today){
            case SUNDAY:
                break;
            case MONDAY:
                break;
            case TUESDAY:
                break;
            case WEDNESDAY:
                break;
            case THURSDAY:
                break;
            case FRIDAY:
                break;
            case SATURDAY:
                break;
            default:
                break;
        }
  
    }
  
    public void setCurrentDay(@WeekDays int currentDay) {
        this.currentDay = currentDay;
    }
  
    @WeekDays
    public int getCurrentDay() {
        return currentDay;
    }
}

使用注解库

这些注解不是默认加载的,它们被包装为一个单独的库。Support Library现在是由一些更小的库组成的,包括:v4-support、appcompat、gridlayout、mediarouter等等。
添加注解的最简单的方法就是打开Project Structure对话框。首先在左边选中module,然后右边选中Dependencies标签,点击“+”号按钮,选择Library Dependency。如果SDK中已经包括了Android Support库,那么注解支持库就会显示在快捷选择列表中了,只需要点击选择就可以。
步骤1:点击Project Structure按钮



步骤2:选中Dependencies标签,点击“+”号按钮


步骤3:在下拉列表中选中support-annotations库


点击OK确定,这将会修改build.gradle文件。当然也可以手动在Gradle中添加如下依赖:
dependencies {
    compile 'com.android.support:support-annotations:23.1.0'
}


你可能感兴趣的:(android开发-基础篇)