Android Support Annotation的使用

发布时间:2019-06-12 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Android Support Annotation的使用脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

http://blog.magicer.xyz/2017/...

官方提供了很多特别好用的类或注解,这里说的support annotation就是特别好的工具,多使用其中的注解,可以规范我们的开发,止一些不必要的错误。要想使用support annotation需要手动添加依赖

compile 'com.andROId.support:support-annotations:25.2.0'

在这里面有几个对我们开发特别有用的注解:

  • @Nullable@NonNull

  • IntDef StringDef

  • 一些资类的注解

这里是官方的教程

Nullable和NonNull

这两个注解还是蛮简单的。字面意思就能看的出来。用于变量,参数和返回值是否为空。
例如

public void foo(@NonNull String content){
        
    }

有这么一个方法,这时候如果我们将参数content的值传入了一个可能为空的值时,编辑器(AS)就会有所提示。

IntDef和StringDef

这两个主要是用来解决在Android中使用enum效率低的问题。这是官方的一个demo。在使用到enum的地方,都应该换成IntDefStringDef

import android.support.annotation.IntDef;
...
public abstract class ActionBar {
    ...
    // define the list of accepted constants and declare the NavigationMode annotation
    @Retention(Retentionpolicy.SOURCE)
    @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
    public @interface NavigationMode {}

    // Declare the constants
    public static final int NAVIGATION_MODE_STANDARD = 0;
    public static final int NAVIGATION_MODE_LIST = 1;
    public static final int NAVIGATION_MODE_TABS = 2;

    // Decorate the target methods wITh the annotation
    @NavigationMode
    public abstract int getNavigationMode();

    // Attach the annotation
    public abstract void setNavigationMode(@NavigationMode int mode);

资源类注解

通过自带的几个资源类注解,可以做到在代码中提示我们使用的资源是否正确。作用在参数上。
主要有@StringRes @DimenRes @IdRes @ColorRes @DrawableRes @AnimRes @AttrRes
@LayoutRes @MenuRes @RawRes等 各类资源的检查注解。
例如,在使用@StringRes之后,会检查该值是不是R.string的形式。

其他

要想查看更加详细的注解,就查看官方文档吧。官方文档讲的比我清楚明了。这里就是简单提一下,做个小笔记。

值约束注解

IntRange FloatRange等,详细看官方文档。这里的代码摘抄自官方文档

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

脚本宝典总结

以上是脚本宝典为你收集整理的Android Support Annotation的使用全部内容,希望文章能够帮你解决Android Support Annotation的使用所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。