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
How do I fix this error?
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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With