4

I don't know why it happens:

If I write the following code:

TextView textView = new TextView(this);
textView.setId(1);

the 1 as id not working and giving me a warning like:

enter image description here

Its not working in following values:

textView.setId(0+1);   // Valid
textView.setId(var++); // Valid even var=0

but not valid

textView.setId(1);     // Invalide

Anyone know about this? Anyone can explain this things?

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437

2 Answers2

1

This warning is generated by android lint. It checks you are using the right type of ID as identifier. Signature for this function is:

public void setId(@IdRes int id)

So, lint checks you are using exactly id of type @IdRes (see IdRes annotation), not @ColorRes or @StringRes (it checks you are using constants from class R.id)

By using expressions like 0+1 or var++ (BTW, it's result actually is 0 not 1) you are hampering lint to infer the argument type.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Alexey
  • 1,198
  • 1
  • 15
  • 35
0

You get a warning because setting your own ID's could be dangerous, you could for example set the same ID as an already existing xml element, this will obviously collide and cause problems. Use View.generateViewId() instead to prevent this.

Jeffalee
  • 1,080
  • 1
  • 7
  • 15
  • Do you think so really?? – Janki Gadhiya Apr 11 '16 at 09:58
  • The name (android:id="...") you give to an xml element is parsed into an integer, this will be a very large number, like 28858383 or something, hypothetically speaking this makes it possible to set a duplicate id to another view programatically. by using the View.generateViewId() method you'll be sure that no ID's will collide with already existing elements. Also if I remember right, the generated ID's will start from 1 and go up. – Jeffalee Apr 11 '16 at 10:04
  • `Possibility` you said. That will be checked on run time not compile time. – Janki Gadhiya Apr 11 '16 at 10:12