当前位置: 代码迷 >> 综合 >> Android 开发 之 Enum (枚举) —— @IntDef的使用
  详细解决方案

Android 开发 之 Enum (枚举) —— @IntDef的使用

热度:110   发布时间:2023-10-24 22:59:04.0
Android 开发 之 Enum (枚举) —— @IntDef的使用
  收藏
 
  • 发表于 2年前 
  • 阅读 6662 
  • 收藏 6 
  • 点赞 0 
  • 评论 0

    官方文档说明,安卓开发应避免使用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;@Overrideprotected 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;}@WeekDayspublic int getCurrentDay() {return currentDay;} }



build.gradle中

compile 'com.android.support:support-annotations:22.0.0'





 

  相关解决方案