Any view that needs to be referenced in either Java code or XML layout requires a unique ID. An ID is defined inside the
android:id attribute. Depending on the situation, it can appear in one of the two forms, either
@id/my_view_id (note that the former has a plus symbol). The same holds true for referencing an already defined ID in the layout, such as when using a
An obvious question arises: When do I use which notation? This has been answered on several websites including StackOverflow. The rule actually sounds quite simple.
When defining a new ID, use the
When referencing an already defined ID, use the
While the above is true, it is somewhat misleading at first. It may trick some people into thinking that one should use the
@+id/my_view_id notation when defining a View, i.e. inside the
android:id attribute, and the
@id/my_view_id version anywhere else. This is completely wrong. In fact, it has nothing to do with anything View related (notice the use of the word ID, as opposed to View in the rule above). It is all about the source code appearance of the ID in the layout and not the context of its usage. That is, the first time an ID is used in the layout regardless of the attribute in which it appears, the “plus notation” must be used. After that, all references to that ID should be in the latter form.
The plus symbol tells the XML parser to generate an integer, which along with the ID (
my_view_id in our example) is used to create a new entry in the
R.java file. Without it, the parser will instead look for an existing entry with the same name. Absence of such mapping will trigger the (in)famous error “No resource found that matches the given name”, which I’m sure every developer has encountered at least a few times.
Some folks have developed a habit of always using the first form (with the plus symbol). This way they don’t have to worry about undefined ID problems or think about ordering Views. It works, but only because of the Android system being forgiving of duplicate IDs, by ignoring further instructions to create a new ID with the same name. However, this may change in the future, which will cause such layouts to become broken. Even if it doesn’t, it may be confusing to other developers. At the very least, it is rather irresponsible, which doesn’t fit well into the Android methodology.
@android notation is used when referencing resources defined by the Android system. You should never use a plus symbol with this notation.
Hope that makes it clear.