Assign a view ID programmatically in Android
Asked Answered
D

4

7

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
Devinne answered 10/7, 2014 at 16:39 Comment(0)
D
11

Found it:

view.setId(View.generateViewId());
Devinne answered 10/7, 2014 at 16:41 Comment(7)
Where do you set "123" as id?Analogous
I don't need 123, I just need a new ID that doesn't conflict with an existing one.Devinne
generateViewId() requires API level 17.Madid
so how do you use that Id later then?Rambow
view.setId(..) sets the view's Id to the value you got by invoking View.generateViewId(). That's it, you used it to assign it to your view.Devinne
@ArtemioRamirez use view.getId()Cynthy
private int viewsCount; mEditTextDynamicTime.setTag(viewsCount); mEditTextDynamicTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int position = (Integer) v.getTag(); Log.d("position====>", String.valueOf(position)); } }); viewsCount++;Expressage
B
4

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://mcmap.net/q/239118/-how-to-set-id-of-dynamic-created-layout so the editor will be happy.
Bichromate answered 13/7, 2014 at 9:20 Comment(0)
F
0

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

Freidafreight answered 15/4, 2015 at 19:26 Comment(0)
L
-1

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.

Lording answered 20/3, 2015 at 20:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.