简体   繁体   中英

Android: programmatically setId is gives a warning Expected resource of type id

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:

在此输入图像描述

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM