Android 中的注解在项目中挺实用的,很多时候可以替换枚举型的数据。 更详细的内容可以去 官方文档
这里举个例子,登陆的角色分另种,一种是店长,另一种是普通的收银员。在整个应用中,需要根据用户类型做出相应的反应时,计较方便了,而不要用到枚举类型。
/** * 用户类型 */ public class UserTypes { @IntDef({SHOP_MANAGER, NORMAL_CASHIER}) @Retention(RetentionPolicy.SOURCE) public @interface UserType{} /** * 店长 */ public static final int SHOP_MANAGER = 1; /** * 普通收银员 */ public static final int NORMAL_CASHIER = 2; }下面是对官方关于注解的一个笔记。
@Nullable, @Nonull
Nullability analysis: . Calling methods that can return null. . Methods, such as fields, local variable and parameters, that can null. . Variables, such as fields, local variable and parameters, that cannot hold a null value.
可以利用 Android Studio 进行检查: Run a null ability analysis: Analyz –> Infer Nullity
这个在方法中可以限制传入的参数类型,防止出错。
@StringRes @DrawableRes @DimenRes @InterpolatorRes
@AnyRes indicates that the annotated parameter can be any type of R resource.
@ColorRes specify that a parameter should be a color resource, a color integer.
@ColorInt to indicate that parameter must be a color integer.
例子:
/** * 获取 Drawable 资源 * @param context * @param dra * @return */ public static Drawable getResourceDrawable(Context context, @DrawableRes int dra){ Drawable drawable = context.getResources().getDrawable(dra); return drawable; } /** * 获取 Color 资源 * @param context * @param color * @return */ public static int getResourceColor(Context context, @ColorRes int color){ Resources resources = context.getResources(); return resources.getColor(color); }@MainThread @UiThread @WarkerThread @BinderThread @AnyThread
@UiThread annotate methods associated with an app’s view hierarchy.
@MainThread annotate only methods associated with an app’s lifecycle.
@IntRange @FloatRange @Size annotations to validate the values of passed parameters.
例子: public void setAlpha(@IntRange(from= 0, to=255) int apha);
public void setAlpha(@FloatRange(from = 0.0, to = 1.0) float alpha);
@Size checks the size of a collection or array, the length of a string. . Minimum size(such as @Size(min = 2)); . Maximum size (such as @Size(max = 2)); . Exact size (such as @Size(2); . A number of which the size must be a multiple(@Size(multipl = 2));
@RequiresPermission to validate the permissions of the caller of a method.
any of 和 all of 结合例子看 any of: 只需要其中一个权限即可 to check for a single permission from list the valid permission.
all of : 所有的权限都要有 to check for a set of permissions.
例子:
@RequiresPermission(Manifest.permission.SET_WALLPAPER) public abstract void setWallpaper(Bitmap bitmap) throws IOException; @RequiresPermission(allOf = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}) public static final void copyFile(String dest, String source);类型定义注解,这类注解最常用在项目中,可以替换枚举类型,文章开头的例子就属于这种类型。 @IntDef @StringDef
在混淆的时候比较有用,防止被混淆掉。 @keep Ensures that an annotated class or method is not removed when the code is minified at build time.