Skip to content

Instantly share code, notes, and snippets.

@utkan
Last active August 14, 2018 11:49
Show Gist options
  • Save utkan/bd8cc3d35881e081d9a5c297b9e21044 to your computer and use it in GitHub Desktop.
Save utkan/bd8cc3d35881e081d9a5c297b9e21044 to your computer and use it in GitHub Desktop.
Typedef Annotations example
@StringDef({
POP,
ROCK,
JAZZ
})
@Retention(RetentionPolicy.SOURCE)
public @interface MusicNameType {}
public abstract class ActionBar {
// Define the list of accepted constants and declare the NavigationMode annotation
@Retention(RetentionPolicy.SOURCE)
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
public @interface NavigationMode {
}
// Declare the constants
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
// Decorate the target methods with the annotation
@NavigationMode
public abstract int getNavigationMode();
// Attach the annotation
public abstract void setNavigationMode(@NavigationMode int mode);
}
public class MainActivity extends AppCompatActivity implements Rocker, RockerNames {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
letsRock(Rocker.POP);
letsRockName(RockerNames.POP);
MyActionBar myActionBar = new MyActionBar();
myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
@Override
public void letsRock(@MusicType int musicType) {
}
@Override
public void letsRockName(@MusicNameType String musicNameType) {
}
}
@IntDef({
POP,
ROCK,
JAZZ
})
@Retention(RetentionPolicy.SOURCE)
public @interface MusicType {}
public class MyActionBar extends ActionBar {
@NavigationMode
private int mode;
@Override
public int getNavigationMode() {
return ActionBar.NAVIGATION_MODE_STANDARD;
}
@Override
public void setNavigationMode(@NavigationMode int mode) {
this.mode = mode;
}
}
public interface Rocker {
public static final int POP = 0;
public static final int ROCK = 1;
public static final int JAZZ = 2;
void letsRock(@MusicType int musicType);
}
public interface RockerNames {
public static final String POP = "POP";
public static final String ROCK = "ROCK";
public static final String JAZZ = "JAZZ";
void letsRockName(@MusicNameType String musicNameType);
}
https://developer.android.com/studio/write/annotations.html?hl=en#enum-annotations
https://gist.github.com/jmarkovic/95c2ad6caddf3c414783
https://www.youtube.com/watch?v=Hzs6OBcvNQE
https://infinum.co/the-capsized-eight/magic-constants-in-android-development
https://guides.codepath.com/android/Replacing-Enums-with-Enumerated-Annotations
https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment