安卓开发应避免使用Enum(枚举类),因为相比于静态常量Enum会花费两倍以上的内存。使用@IntDef注解来代替枚举是个不错的选择。
添加android注解依赖:
compile 'com.android.support:support-annotations:25.1.0'
使用:
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;
}
}
public class Toast {
static final String TAG = "Toast";
static final boolean localLOGV = false;
/** @hide */
/*定义部分*/
@IntDef({LENGTH_SHORT, LENGTH_LONG})
@Retention(RetentionPolicy.SOURCE)
public @interface Duration {}
public static final int LENGTH_SHORT = 0;
public static final int LENGTH_LONG = 1;
...
/*作为类型使用时*/
/**
* Set how long to show the view for.
* @see #LENGTH_SHORT
* @see #LENGTH_LONG
*/
public void setDuration(@Duration int duration) {
mDuration = duration;
}
/*做为返回值时*/
/**
* Return the duration.
* @see #setDuration
*/
@Duration
public int getDuration() {
return mDuration;
}
}
public class MainActivity extends AppCompatActivity{
public static final int STATE_NONE = -1;
public static final int STATE_LOADING = 0;
public static final int STATE_SUCCESS = 1;
public static final int STATE_ERROR = 2;
public static final int STATE_EMPTY = 3;
private @State int state;
public void setState(@State int state){
this.state = state;
}
@State
public int getState() {
return this.state;
}
@IntDef({STATE_EMPTY, STATE_ERROR, STATE_LOADING, STATE_NONE, STATE_SUCCESS})
@Retention(RetentionPolicy.SOURCE)
public @interface State {
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}