Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 806
cheesus Avatar asked Jul 10 '14 16:07

cheesus


People also ask

How to dynamically add views into view in Android?

How to Dynamically Add Views into View in Android? This example demonstrates How to Dynamically Add Views into View. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

How to add view binding in Android Studio?

Add View Binding dependency inside the build.gradle (app) and click on the sync now button. .. Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that it has a Linear Layout with id parent_linear_layout which we will inflate to add our views.

How to add edittext view programmatically in todo list?

Here, the Text View is holding a simple text as "Todo List" and after that, the Empty Linear Layout having id of container, this linear layout is the place where we have to insert the EditText View programmatically, for now let it be empty. And then finally we have our "Add Task" Button to add the EditText in the empty Linear Layout.

How to add Kotlin view binding to Android app?

Note that select Kotlin as the programming language Add View Binding dependency inside the build.gradle (app) and click on the sync now button. .. Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.


2 Answers

Found it:

view.setId(View.generateViewId());
like image 149
cheesus Avatar answered Oct 10 '22 09:10

cheesus


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.
like image 35
Eslam Sameh Ahmed Avatar answered Oct 10 '22 10:10

Eslam Sameh Ahmed