AndroidStudio--编译出错-Expected resource of type styleable [ResourceType]

时间:2022-03-22 15:52:44

前言:


在使用TypedArray获取数据属性值的时候,编译时出现错误,但是能正常调试,但是使用gradle打包apk的时候,会被检查出来,导致打包失败


异常信息:


   编译时:   Expected resource of type styleable [ResourceType]


   AndroidStudio--编译出错-Expected resource of type styleable [ResourceType]

AndroidStudio--编译出错-Expected resource of type styleable [ResourceType]


   gradle打包apk出现错误:


AndroidStudio--编译出错-Expected resource of type styleable [ResourceType]


异常解决:


  在使用TypedArray的语句,方法上或者类上加上注解@SuppressWarnings("ResourceType")



异常思考:


关于错误:

首先看一下,编译时的提示的错误信息:


  • This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations. 
  • Examples of errors flagged by this inspection:
  • Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
  • Forgetting to invoke the overridden method (via super) in methods that require it
  • Calling a method that requires a permission without having declared that permission in the manifest
  • Passing a resource color reference to a method which expects an RGB integer value.


英语再渣也要的翻译的我是这样理解的:

  •   API中有很多种注解,这些注解在一定程度上规定了某些方法使用,例如要求声明某个权限或者必须是UI主线程中调用等,如果没有正确按照API的方法上的注解规定使用,就是出现这个错误的提示信息
  •   例如:
  •   api要求使用R.dimen,你却使用了R.string;
  •   重写了父类的方法,但是没有加override/supper关键词
  •   使用了要求有某种权限的方法,但是这个权限在配置文件manifest中没有声明
  •   要求使用RGB颜色值作参数的方法你使用了资源颜色


我们这个方法的提示信息是Expected resource of type styleable [ResourceType]

也就是说我们是因为违反了[ResourceType]这个规定,因为getDimension(int,int)想要的参数是资源类型,就是R.XX.XX的这种,但是我们这里直接传递的是int类型,虽然都是int类型的,但是不是他想要的,就报错了,这里实验一下,当我们传递一个int类型的R.styleable.XX,这个提示信息就消失了,看下面:


AndroidStudio--编译出错-Expected resource of type styleable [ResourceType]


关于解决方法:


 SuppressWarning("XXX")


 方法的作用是告诉编译器,一个让类型的警告不再显示.参数"XXX",就是指定某种类型的警告.

 就像我们的使用SuppressWarning("ResourceType"),就是说不要再报关于ResourceType类型的警告错误了.


这里有人也许会问,本来编译器提示的错误,我们不解决,直接这样简单粗暴的让他不再显示会不会有问题,答案是,不会.

原因是:

1.从方法的参数类型上看,都是要求int类型,我们传入的也是int类型,这点没有错误

2.从方法的参数值上看,即使按方法api规定传入R.XX.XX,当程序运行的时候,传入方法的也是R.XX.XX代表的实际值,和我们直接给数据是一样的.相当于我们知道R.XX.XX的实际值是64,我们就直接给64.和使用R.XX.XX的结果是一样的.