3

As explained in http://tools.android.com/tips/non-constant-fields, resource ids are not final (in ADT 14). So a check with switch is broken (see: Android resource IDs suddenly not final, switch()'es broken). However after opening R.java you can see that there are final resources. So, what to use - if or switch? What versions of SDK require if statement? A Lint does not alert if I write

switch (v.getId()) {
    case R.id.llBirthday:
        ...
        break;
    case R.id.llCity:
        ...
        break;
}
Community
  • 1
  • 1
CoolMind
  • 26,736
  • 15
  • 188
  • 224
  • 1
    Both will work, i guess its a question of preference. When you refer to R.id.SomeId, You are referring to R, and R is generated when you compile your app, so it should always work. It's been practice with google for a while now. For safety i always use if, because case is dependent on primitive int – Mushroomzier Dec 18 '15 at 10:05

2 Answers2

1

The ids are converted to a unique integer value and by switching on the value of R.id.myvalue that int value will always map to that resource.

The linked question is from 2011.

As for if or switch, if you have only a couple of values then an if statement might be better, a longer list then a switch, which is programming basics. Please note this is not set in stone. When to use If-else if-else over switch statments and vice versa

Community
  • 1
  • 1
  • 1
    Thank you, Ms Yvette, I understand. So, I think, Google changes of 2011 are now deprecated and we can use *switch*. – CoolMind Dec 18 '15 at 10:10
1

We can use if else or switch both and both will work. And as you are using R.id.yourResource which will convert to an int thats why both if else and switch work.

Pankaj
  • 7,908
  • 6
  • 42
  • 65
  • I agree with you. I was fearing that an app could fail in some cases if using switch. But Google restored *final* in R.java, so no problem again. – CoolMind Dec 18 '15 at 10:15