Android Toast
的duration(int)
传参只能是Taost.LENGTH_SHORT
和Taost.LENGTH_LONG
,这个是怎么实现的呢?
查看源码
public static final int LENGTH_SHORT = 0;
public static final int LENGTH_LONG = 1;
@IntDef({LENGTH_SHORT, LENGTH_LONG})
@Retention(RetentionPolicy.SOURCE)
public @interface Duration {}
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
return makeText(context, null, text, duration);
}
duration 的参数前面有个注解@Duration
而这个@Duration
中又有个注解@Intdef
@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface IntDef {
/** Defines the allowed constants for this element */
long[] value() default {};
/** Defines whether the constants can be used as a flag, or just as an enum (the default) */
boolean flag() default false;
}
@Intdef
是 android.support.annotation
包下的一个注解,@Target({ANNOTATION_TYPE})
表明它只能用来修饰注解.android.support.annotation
包下有很多预定义的注解可以使用,能够帮你检查代码,比如@MainThread
,`@IntRange” 等.
如果你写了个方法,并且只想让调用者传入固定的几个值,那么就可以参照Toast
中的写法.
1,把值定义成常量
2,写一个注解,用@Indef
引用你写的那几个常量
3,用刚写的注解修饰你需要限定的传参
eg:
//参照 Taost
如果你只是想限制一个取值范围,比如(0~100)那么你可以用@IntRange(from 0,to 100)
那么调用者就不能够传参这个范围以外的值
eg:
public static void input(@IntRange(from 0,to 100) int i){
//do something
}
这些注解只会保留到源码级别,不会对运行时造成影响.