Android代码中应该使用的一些Annotation

本文主要整理自https://blog.mindorks.com/improve-your-android-coding-through-annotations-26b3273c137a

Android中使用Annotation不仅可以提高代码的可读性,还有很多其他的功能。下面介绍几个常用的Annotation

1. @Nullable和@NonNull

这两个是最常见的Annotation,用于检查变量、参数或者返回值是否可以为空。

@NonNull
public View getView(@Nullable String s1, @NonNull String s2) {
  // s1 可以为 null
  // s2 不可以为 null
  // 方法必须返回一个非null 的View
}

2. 资源注解

我们知道Android中资源id都是int值,如果有些参数是资源id,如果只是设置为int类型则容易造成误用,这时可以使用资源注解:

public void setText(@StringRes int resId) {
  // resId必须是一个string id,而不可以是普通的int值,或者其他类型的资源id
}

3. 线程注解

线程注解可以检测方法的调用者是否是某一个特定的线程,目前支持的注解包括:

@MainThread
@UiThread
@WorkerThread
@BinderThread
@AnyThread

@WorkerThread
public void doSomething(){
  // this method must be called from the worker thread
}

4. 值域注解

有时方法的参数会限定在一定的范围,可以使用值域注解:@Size, @IntRange, @FloatRange

public void setAlpha(@IntRange(from=0,to=255) int alpha) {}

5. 权限注解

使用@RequiresPermission 验证方法的调用者是否已经申请权限:

@RequiresPermission(Manifest.permission.SET_WALLPAPER)
public abstract void setWallpaper(Bitmap bitmap) throws IOException;

如果方法的调用这没有在manifest中申请SET_WALLPAPER,则会显示警告。

6. Typedef注解

除了资源类型,int有时可以类似枚举类型,如下例子:

    private final static int GET=0;
    private final static int POST=1;
    private final static int DELETE=2;
    private final static int PUT=3;
    @IntDef({GET, POST, DELETE,PUT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface ReqType{}

使用@IntDef可以限制方法的调用方使用特定的参数。

    原文作者:wutongke
    原文地址: https://www.jianshu.com/p/df5c78efe855
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞