美文网首页安卓开发
使用 Android Support Annotations避免

使用 Android Support Annotations避免

作者: 蓝不蓝编程 | 来源:发表于2018-10-12 08:58 被阅读7次

背景:

项目中有一个公用类,支持设置View的背景,第二个入参是颜色。

public static void setBackgroundColor(View view, int color) {
    view.setBackgroundColor(color);
}

  1. 初次使用时,使用了如下的传参方式,直接将color的资源id传入了,但是却发现显示出来的颜色不对。
    setBackgroundColor(button,R.color.color_3F51B5);

上面代码对应的效果如下图按钮背景:


image.png
  1. 后来才发现传参错误,应该穿color值,而不是color资源ID。

setBackgroundColor(button,ContextCompat.getColor(context,R.color.color_3F51B5));

预期效果如右图按钮背景: image.png

思考:

虽然找到了问题原因,但是这样的错误很容易犯,是否有更好避免此类问题的方法呢?

解决方案:

1.引入annotations包依赖,如:compile "com.android.support:support-annotations:28.0.0"

implementation "com.android.support:support-annotations:28.0.0"
2.可以对输入参数增加注解,供编译环节校验参数合法性。修改代码定义,对color参数增加@ColorInt注解:

public static void setBackgroundColor(View view,@ColorInt int color) {
        view.setBackgroundColor(color);
    }
image.gif

继续思考:

除了上面的注解,是否还有其他类似的注解?

全量注解介绍:

| AnimatorRes | 表示int类型的参数,成员变量,或方法返回值是一个animator资源的引用 |
| AnimRes | 表示int类型的参数,成员变量,或方法返回值是一个anim资源的引用 |
| AnyRes | 表示int类型的参数,成员变量,或方法返回值是一个任意资源类型的引用 |
| ArrayRes | 表示int类型的参数,成员变量,或方法返回值是一个array资源类型的引用 |
| AttrRes | 表示int类型的参数,成员变量,或方法返回值是一个attr资源的引用 |
| BoolRes | 表示int类型的参数,成员变量,或方法返回值是一个boolean资源的引用 |
| ColorRes | 表示int类型的参数,成员变量,或方法返回值是一个color资源的引用 |
| DimenRes | 表示int类型的参数,成员变量,或方法返回值是一个dimen资源的引用 |
| DrawableRes | 表示int类型的参数,成员变量,或方法返回值是一个drawable资源的引用(包括@mipmap) |
| FractionRes | 表示int类型的参数,成员变量,或方法返回值是一个fraction资源的引用 |
| IdRes | 表示int类型的参数,成员变量,或方法返回值是一个id资源的引用 |
| IntegerRes | 表示int类型的参数,成员变量,或方法返回值是一个int类型资源的引用 |
| InterpolatorRes | 表示int类型的参数,成员变量,或方法返回值是一个interpolator资源的引用 |
| LayoutRes | 表示int类型的参数,成员变量,或方法返回值是一个layout资源的引用 |
| MenuRes | 表示int类型的参数,成员变量,或方法返回值是一个menu资源的引用 |
| PluralsRes | 表示int类型的参数,成员变量,或方法返回值是一个plurals资源的引用 |
| RawRes | 表示int类型的参数,成员变量,或方法返回值是一个raw资源的引用 |
| StringRes | 表示int类型的参数,成员变量,或方法返回值是一个string资源的引用 |
| StyleableRes | 表示int类型的参数,成员变量,或方法返回值是一个styleable资源的引用 |
| StyleRes | 表示int类型的参数,成员变量,或方法返回值是一个style资源的引用 |
| TransitionRes | 表示int类型的参数,成员变量,或方法返回值是一个transition资源的引用 |
| XmlRes | 表示int类型的参数,成员变量,或方法返回值是一个xml资源的引用 |
| ColorInt | 表示int颜色值 |
| IntRange | 表示参数需要在给定的int或long范围内 |
| FloatRange | 表示参数需要在给定的float范围内 |
| NonNull | 表示参数不能为null |
| Nullable | 表示参数可以为null |
| Dimension | 表示int类型的参数,成员变量,或方法的返回值是尺寸大小 |
| Px | 表示int类型的参数,成员变量,或方法的返回值是像素大小 |
| CallSuper | 只用在方法上,表示任何重写该方法的子类,也应该调用该方法 |
| CheckResult | 用来验证是否使用了方法返回值,可以通过添加注释来进行提示 |

相关文章

网友评论

    本文标题:使用 Android Support Annotations避免

    本文链接:https://www.haomeiwen.com/subject/bvrwaftx.html