7

While looking at the answer here, I was having problems on the line:

TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs);

It seems that Android Studio won't let me pass in an int that doesn't come from a R.styleable resource without gettings warnings.

It tells me that it expects a resource of type styleable, which I assume means that the code I'm calling has been annotated with the @StyleableRes annotation

Expected resource of type styleable

What would be the best course of action to read the values defined in the R.style.{x}? The accepted answer on the linked post works and compiles, but I don't know how to suppress the warning. As there's a warning, is it safe to suppress? If so, how?

Community
  • 1
  • 1
Ben Pearson
  • 7,532
  • 4
  • 30
  • 50
  • A `styleable` is not a `style` – Blackbelt Oct 14 '14 at 12:41
  • @blackbelt correct. That's why I'm confused that the accepted (bounty!) answer in the question I linked to is using a style and has so many upvotes. – Ben Pearson Oct 14 '14 at 12:43
  • in fact it's just a warning, did you run your code? – pskink Oct 14 '14 at 13:56
  • The code compiles. For the moment, I'm using @SuppressWarnings("all"), but it's not ideal. I want to explicitly say in the code "I'm aware of this warning and it can be ignored" but only for that one call on obtainStyledAttributes. I could create a method containing only that line to extract the TypedArray and annotate that method, but it's seems like a work around. – Ben Pearson Oct 14 '14 at 16:13

2 Answers2

9

I think the correct way to suppress this :

@SuppressWarnings("ResourceType")

I'm offered this when I press Alt-Enter to bring up fixes for the warning and choose Inspection 'Constant and Resource Type Mismatches' options > Suppress for class (screenshot attached)enter image description here.

It works for me.

It's possible that the ID for this inspection has changed since whatever code you were referencing was written; I looked briefly through the commit logs but couldn't find a reference to it.

Scott Barta
  • 79,344
  • 24
  • 180
  • 163
  • Thanks for the answer. I've suppressed that specific warning now. Is it safe to mute the warning (I'm guessing it's a warning for a reason)? – Ben Pearson Oct 15 '14 at 09:52
  • You might not want to mute it everywhere all the time. This bug notwithstanding, it does flag an easy-to-make but difficult-to-diagnose programming error. – Scott Barta Oct 15 '14 at 15:51
  • Set that suppression to method is enough and safer .. no need to take it wild to whole class.. – Maher Abuthraa Sep 06 '16 at 08:26
1

You can suppress warning checking with @SuppressWarnings("ResourceType") for the method in which the problem is or you can just use //noinspection ResourceType just before that line to avoid inspection only in that line of code.

Hugo
  • 1,662
  • 18
  • 35