Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve error: "Resource IDs cannot be used in switch statement in Android library modules" [duplicate]

I imported a Android project created by someone else into my project as a library module. I get the following error even after cleaning and rebuilding project:

Constant expression required Resource IDs cannot be used in switch statement in Android library

enter image description here

How do I fix this error?

like image 350
Gp Master Avatar asked Jul 18 '18 12:07

Gp Master


2 Answers

Your main problem here is that switch statements require constant values as comparators, be it either a literal value e.g. 1, "hello" or a final variable declared at class level. Android R.id values have not been constant since API 14, as stated in that error message, so therefore cannot be used as part of a switch statement.

Your alternative would be to use if else statements as they do not require constant values, like so:

if (v.getId() == R.id.something) {
    // Do something
} else if (v.getId() == R.id.something_else) {
   // Do something else
}
// Repeat however many times required
else {
   // Default value
}
like image 124
Michael Dodd Avatar answered Sep 17 '22 17:09

Michael Dodd


You can set a tag for each view and use the tag in the switch case. Something like this:

In your view:

...
android:tag="test" />

In code:

switch(v.getTag()){
    case "test":
    // Do Something
    break;
}
like image 32
Hamlet Leon Avatar answered Sep 21 '22 17:09

Hamlet Leon