Android IntDef and StringDef annotations

This article just wants to let myself remember these two notes. I've seen them several times before, and I don't need to forget them. It's strange to see them again. Use this blog to remember them. Let's talk about these two notes. It's clear that in Android, enum is not recommended officially because it occupies a relatively large amount of memory. For memory eating applications, we may choose static constant light. But in some places, we just want it to give a specified range of values. At this time, there is no way to check the static constant It's not the value you want. At this time, you can use these two annotations to complete it. It will check whether our assignment meets the requirements when compiling. Discover errors in advance.
Add dependency
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
...
compile 'com.android.support:support-annotations:22.0.0'
}

Then write the
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({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;
}

}
It's very convenient to use
in same manner of StringDef and IntDef

Tags: Android

Posted on Tue, 05 May 2020 18:41:38 -0700 by lm_a_dope