美文网首页理解记忆Android基础知识
@SuppressLint("NewApi")、@TargetA

@SuppressLint("NewApi")、@TargetA

作者: 肖霄的潇潇 | 来源:发表于2020-02-23 19:40 被阅读0次

    官方解释
    1.@TargetApi
    Indicates that Lint should treat this type as targeting a given API level, no matter what the project target is. @apiSince 16
    (指示Lint应将此类型视为针对给定API级别,而不管项目目标是什么。@apiSince 16)

    2.SuppressLint
    Indicates that Lint should ignore the specified warnings for the annotated element.
    (指示Lint应该忽略带注释的元素的指定警告。)

    3.RequiresApi
    Denotes that the annotated element should only be called on the given API level or higher.

    This is similar in purpose to the older @TargetApi annotation, but more clearly expresses that this is a requirement on the caller, rather than being used to "suppress" warnings within the method that exceed the minSdkVersion.
    (表示只应在给定API级别或更高级别上调用带注释的元素。
    这在目的上与旧的@TargetApi注释相似,但更清楚地表示这是调用者的需求,而不是用于“抑制”方法中超过minSdkVersion的警告。)

    @SuppressLint("NewApi")屏蔽一切新api中才能使用的方法报的android lint错误。@TargetApi() 只屏蔽某一新api中才能使用的方法报的android lint错误。@RequiresApi与旧版@TargetApi注释的目的相似,但更清楚表示这是调用者的要求,而不是用于“抑制”警告。(其它方面基本没有区别)

    举个例子,某个方法中使用了api 9新加入的方法,而项目设置的android:minSdkVersion = 8 ,此时在方法上加 @SuppressLint("NewApi")和@TargetApi(Build.VERSION_CODES.GINGERBREAD)都可以,以上是通用的情况。而当你在此方法中又引用了一个api 11才加入的方法时,@TargetApi(Build.VERSION_CODES.GINGERBREAD)注解的方法又报错了,而@SuppressLint("NewApi")不会报错,这就是区别。

    以上就是三者的区别比较,个人建议直接使用@SuppressLint("NewApi")。当然了注解的作用只是让编译通过,而并没有避免低版本的系统运行高版本的api的问题,在使用时我们需要自己判断版本号来使用不同版本的api。
    

    作者:指尖力量
    链接:https://www.jianshu.com/p/531c2899c823
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

        本文标题:@SuppressLint("NewApi")、@TargetA

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