简体   繁体   中英

Assign a view ID programmatically in Android

I'm trying to create a RelativeLayout with several children programmatically. To make the rules like RelativeLayout.RIGHT_OF work, the child views must have proper IDs.

However, when I try to assign an ID, Android Studio flags it as an error:

view.setId(123);

ERROR: Expected resource of type id

找到了:

view.setId(View.generateViewId());

You have two options:

  1. This is not a compiler error. It is just editor validation error as this is not a common way to deal with Ids. So compile and run with no problems
  2. Use pre-defined list of Ids with type "id" as this accepted answer https://stackoverflow.com/a/8937477/1657333 so the editor will be happy.

In Android Studio click on lightbulb on line with this 'error'. And select 'Disable inspection' in first submenu.

As others have said, you shouldn't be using Integers directly in this case. There are some very rare cases where you might need to do this or in general suppress validation warnings. If so then you need to look into Lint . In Android Studio you can click on the red light bulb at the left side of the line of code. This will show a context menu with a list of methods of suppression.

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