Jonas Sourlier
Jonas Sourlier

Reputation: 14435

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

Upvotes: 7

Views: 11598

Answers (4)

Eslam Sameh Ahmed
Eslam Sameh Ahmed

Reputation: 4012

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.

Upvotes: 4

Tapa Save
Tapa Save

Reputation: 4857

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

Upvotes: 0

Michael Simonds
Michael Simonds

Reputation: 11

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.

Upvotes: -1

Jonas Sourlier
Jonas Sourlier

Reputation: 14435

Found it:

view.setId(View.generateViewId());

Upvotes: 11

Related Questions