Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio's "expected resource of type" checks?

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?
like image 891
matiash Avatar asked Jul 12 '14 19:07

matiash


1 Answers

(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:

  • Video from Google I/O 2014: What's new in Android development tools
like image 92
matiash Avatar answered Oct 02 '22 12:10

matiash