Android的Studio的"类型&QUOT预期得到的资源;检查? [英] Android Studio's "expected resource of type" checks?

查看:198
本文介绍了Android的Studio的"类型&QUOT预期得到的资源;检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android的工作室测试版(0.8)有一个漂亮的新功能,它检查一些 INT 参数不任意整数,而是具有一定的属性。

例如,要求是这样的:

 的setContentView(R.id.textView1);
 

将正确报告 R.id.textView1 不是一个布局ID(该消息为布局的预期资源)。还有这等情况下,穿插各地。

可以理解的,这种保护是,只要你添加自己的方法混进去丢失,如:

 私人无效mySetContentView(INT RESOURCEID){
    的setContentView(RESOURCEID);
}
 

我可以调用 mySetContentView()与任意整数,也不会抱怨。

所以,我有两个(相关的)问题:

  1. 这是如何实现的? - 是的专项检查烤成皮棉
  2. 有什么办法来注释 mySetContentView()方法,以便与无效值?
  3. 调用它时,它也会报告资源类型错误
解决方案

(感谢@CommonsWare的单挑)。

有Java注释支持这些检查在自己的code。他们可以在 android.support.annotations 包中的所有发现:

  • IdRes
  • DrawableRes
  • LayoutRes
  • StringRes
  • 和C

在此情况下,例如,我可以使用:

 私人无效mySetContentView(@LayoutRes INT RESOURCEID){
    的setContentView(RESOURCEID);
}
 

和Android Studio将检查所提供的资源ID确实是一个布局。

此外,这些注解出口,所以设计一个文库时,他们可以是特别有用的。

来源:

Android Studio Beta (0.8) has a nifty new feature where it checks that some int parameters are not arbitrary integers, but rather have some properties.

For example, calling something like:

setContentView(R.id.textView1);

will correctly report that R.id.textView1 is not a layout id (the message is "expected resource of type layout"). There are other cases of this peppered around.

Understandably, this protection is lost as soon as you add your own methods into the mix, e.g.

private void mySetContentView(int resourceId) {
    setContentView(resourceId);
}

I can then call mySetContentView() with any arbitrary integer and it will not complain.

So, I have two (related) questions:

  1. How is this achieved -- are the special checks "baked" into lint?
  2. Is there any way to annotate the mySetContentView() method so that it will also report a resource type error when calling it with an invalid value?

解决方案

(Thanks to @CommonsWare for the heads up).

There are Java annotations to support these checks in your own code. They can all be found in the android.support.annotations package:

  • IdRes
  • DrawableRes
  • LayoutRes
  • StringRes
  • &c

In this case, for example, I could use:

private void mySetContentView(@LayoutRes int resourceId) {
    setContentView(resourceId);
}

and Android Studio will check that the provided resource id is indeed for a layout.

Moreover, these annotations are exported, so they can be especially useful when designing a library.

Sources:

这篇关于Android的Studio的"类型&QUOT预期得到的资源;检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆