Android@IntDefの使用-列挙の代わりに

2230 ワード

Android@IntDefの使用-列挙の代わりに
公式文書によると、アンドロイド開発では、静的定数Enumよりも2倍以上のメモリがかかるため、Enum(列挙クラス)の使用は避けるべきだという.[参考]では、Enumを使う必要がある場合はどうすればいいのでしょうか.
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;
    }
}

依存性が欠けている場合はbuild.gradleに次の依存性を追加します.
compile ‘com.android.support:support-annotations:22.0.0‘

Stringタイプ
stringタイプはintタイプと似ています@StringDefを使えばいいです
@StringDef({DepositStatus.PAID, DepositStatus.UNPAID, DepositStatus.FREE, DepositStatus.EXPIRE})
@Retention(RetentionPolicy.SOURCE)
public @interface DepositStatus {
    String PAID = "PAID"; 
    String UNPAID = "UNPAID";
    String FREE = "FREE"; 
    String EXPIRE = "EXPIRE"; 
}

転載先http://www.bubuko.com/infodetail-1070320.html