註解是一種元數據, 可以添加到java代碼中. 類、方法、變量、參數、包都可以被註解,註解對註解的代碼沒有直接影響。我們最經常看到的就是@Override了……
Android註解官方文檔:https://developer.android.com/studio/write/annotations.html。
AndroidAnnotations框架:http://androidannotations.org/。
Butter Knife框架:http://jakewharton.github.io/butterknife/。
其他如:XUtils框架等。
需要dependencies { compile
‘com.android.support:support-annotations:22.2.0’
}。22.2.0版本根據需要更改。如果引入了appcompat就不需要了(appcompat包含support-annotations)。
- Nullness註解,主要有兩種@Nullable和@NonNull。
- 資源類註解(限定爲對應資源的id):@AnimRes,@AnimatorRes,@AnyRes,@ArrayRes,@AttrRes,@BoolRes,@ColorRes,@DimenRes,@DrawableRes,@FractionRes,@IdRes,@IntegerRes,@InterpolatorRes,@LayoutRes,@MenuRes,@PluralsRes,@RawRes,@StringRes,@StyleRes,@StyleableRes,@TransitionRes,@XmlRes
。 - @CallSuper:必須調用父類對應方法。
- 權限註解如:@RequiresPermission(Manifest.permission.SET_WALLPAPER)。
- 枚舉註解:@IntDef和@StringDef。
- 替代findViewById(Butter
Knife框架):需要自定義註解如@ViewInject或者@InjectView。例子:http://www.cnblogs.com/punkisnotdead/p/4705258.html。 - 區間範圍註解:@IntRange、@ FloatRange。
- 長度以及數組大小限制:@Size(6) String key和@Size(max = 1) String[]
data以及@Size(multiple = 3) String[] data。 - 方法返回結果未被使用:@CheckResult。
- 線程相關:@UiThread,@MainThread,@WorkerThread,@BinderThread。
自定義註解:
http://www.jianshu.com/p/a13c6326671d;
http://www.jianshu.com/p/8f4fb5675eff。