Error: Expected resource of type raw [ResourceType]

来源:互联网 发布:乐清人民法院淘宝拍卖 编辑:程序博客网 时间:2024/05/18 17:01

问题

       工程里面用到了将一个drawable图片当做输入流来使用:

InputStream inputStream = getResources().openRawResource(R.drawable.guide1);

       在debug包使用的时候是没有问题的,但是一旦打release包的时候就会打包失败,提示:

Error: Expected resource of type raw [ResourceType]

       但是看代码,函数名称虽然名称是openRawResource, 但是妥妥可以可以设置drawable类型啊.

/** * Open a data stream for reading a raw resource.  This can only be used * with resources whose value is the name of an asset files -- that is, it can be * used to open drawable, sound, and raw resources; it will fail on string * and color resources. *  * @param id The resource identifier to open, as generated by the appt *           tool. *  * @return InputStream Access to the resource data. * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. *  */public InputStream openRawResource(@RawRes int id) throws NotFoundException {    final TypedValue value = obtainTempTypedValue();    try {        return openRawResource(id, value);    } finally {        releaseTempTypedValue(value);    }}

       注释里面妥妥的写了drawable可以,跟踪代码最终到了AssetManager也是可以的,从这里可以明确的知道错误不是代码出现的,是IDE对代码进行了检查。发现这里需要一个raw资源,而我们传入了其他类型的资源,因此报错。

解决方案

       既然是IDE做了检查,那我们可以绕过该检查就可以了。

方法1

       对代码的设置@SuppressWarnings("ResourceType")来消除警告

方法2

       我们可以在build.gradle的Android节点下加入如下配置:

android { lintOptions {    disable "ResourceType"  }}

       lint检查的时候,去掉资源类型检查

方法3

       既然该函数要求一个raw资源,那就放置一个资源到raw目录下,之后使用该资源:

InputStream inputStream = getResources().openRawResource(R.drawable.guide1);//替换成InputStream inputStream = getResources().openRawResource(R.raw.guide1);

方法4

       
InputStream is = getResources().openRawResource(+ R.drawable.guide1);

       我也是第一次见到这个使用方式,前面加”+”号,stackoverflow上有人回答说:他主要采用某种方法将一个drawable文件转换为一个raw文件,而不需要创建一个raw目录。

       但是我怎么感觉这更像是一个小技巧,只是骗过了IDE的检查。没有找到对应的文档

阅读全文
0 0
原创粉丝点击