Android中常见的一些注解

947 阅读3分钟

Nullness注解

@Nullable

作用于方法的参数或返回值,标记参数或返回值可空

@Nullable
public String hello(){}

public String print(@Nullable String msg){}

@NonNull

作用于方法的参数或返回值,标记参数或返回值不可为空

@NonNull
public String hello(){}

public String print(@NonNull String msg){}

资源注解

@AnimatorRes

标记整型值是android.R.animator类型

@AnimRes

标记整型值是android.R.anim类型

@AnyRes

标记整型值是任何一种资源类型

@ArrayRes

标记整型值是android.R.array类型

@AttrRes

标记整型值是android.R.attr类型

@BooRes

标记整型值是布尔类型

@ColorRes

标记整型值是android.R.color类型

@DrawableRes

标记整型值是android.R.drawable类型

@FractionRes

标记整型值是fraction类型,用在动画资源文件中,如50%p,表示占parent的50%

@IdRes

标记整型值是android.android.id类型

@IntegerRes

标记整型值是android.android.integer类型

@InterpolatorRes

标记整型值是android.android.interpolator类型

@LayoutRes

标记整型值是android.android.layout类型

@MenuRes

标记整型值是android.android.menu类型

@PluralsRes

标记整型值是android.android.plurals类型,复述字符串类型

@RawRes

标记整型值是android.android.raw类型

@StringRes

标记整型值是android.android.string类型

@StyleableRes

标记整型值是android.android.styleable类型

@StyleRes

标记整型值是android.android.style类型

@TransitionRes

标记整型值是transition类型

@XmlRes

标记整型值是android.android.xml类型

举个🌰

public void setBackgroundColor(@ColorRes int backgroundColor){}
public void setContentView(@LayoutRes int layoutResID) {}

类型定义注解

@IntDef

用于限定int值为指定数据集内的值,举个🌰

public class Test {
    @Retention(RetentionPolicy.SOURCE)
    @IntDef(value = {TYPE_FILE, TYPE_IMAGE, TYPE_VIDEO})
    public @interface MediaType {
    }

    public static final int TYPE_FILE = 0;
    public static final int TYPE_IMAGE = 1;
    public static final int TYPE_VIDEO = 2;
    @MediaType
    private int mMediaType = TYPE_FILE;

    public void setMediaType(@MediaType int mediaType) {
        mMediaType = mediaType;
    }

    @MediaType
    public int getMediaType() {
        return mMediaType;
    }
}

setMediaType 只能传入TYPE_FILE,TYPE_IMAGE,TYPE_VIDEO三种类型的值。

线程注解

@UiThread

标记运行在UI线程。

@UiThread
public class View implements Drawable.Callback, KeyEvent.Callback,
        AccessibilityEventSource {
     // ... 
}

@MainThread

标记运行在主线程。

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner,
        ActivityResultCaller {
    // ...
    @MainThread
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    }
    
    // ...
}

@WorkerThread

标记运行在子线程。

@SystemService(Context.STORAGE_SERVICE)
public class StorageManager {
    @WorkerThread
    public void allocateBytes(FileDescriptor fd, @BytesLong long bytes) throws IOException {
    }
}

@BinderThread

标记运行在Binder线程。

class IInputMethodWrapper extends IInputMethod.Stub
        implements HandlerCaller.Callback {
    @BinderThread
    @Override
    public void showSoftInput(IBinder showInputToken, int flags, ResultReceiver resultReceiver) {
    }
}

RGB颜色值注解

@ColorInt

public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
    public void setTextColor(@ColorInt int color) {
    }
}

值范围注解

@Size

限制数组集合等参数的范围大小
@Size(min=1) 集合最少得有一个元素 @Size(max=8) 集合最多只能有8个元素 @Size(2) 集合大小是2 @Size(multiple=2) 集合大小是2的倍数

IntRange

限制参数类型范围

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

FloatRange

限制参数类型范围

public void setAlpha(@FloatRange(from=0.0,to=1.0) float alpha){}

权限注解

@RequirePermission

提示需要某些权限

@RequiresPermission(anyOf = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
public void saveImage(byte[] bytes) { }

重写函数注解

@CallSuper

提示重写方法后必须调用父类方法,否则会出错

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback,
        AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {
    @MainThread
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {}
}

返回值注解

@CheckResult

提示方法调用者注意检查返回值

public abstract class PackageManager {
    @CheckResult
    @PermissionResult
    public abstract int checkPermission(@NonNull String permName,
            @NonNull String packageName);
}

@VisibleForTesting

用于标记不可见的类、方法、变量在测试时可见

@Keep

用于标记类防止被混淆