views:

646

answers:

2

We all know that when generating an id for Android using

@+id/foo

Android creates for us an entry in R.java like:

 public static final class id {
        public static final int foo=0x7f060005;
 }

What happens if there is a name collision in different xml files (let's say, inside two layouts)? The @+id mechanism ensures us to overwrite the id name if another one still exist, but which one is generated in R.java for us?

+2  A: 

I think it simply reuses the identifier if it's already generated. I tend to reuse IDs quite a bit, and have never run into a problem.

Erich Douglass
It reuses it means that it overwrites the entry in R.java if another one is present. How does Android decide which one to keep and which one to delete, at compile time?
bodom_lx
This question is meaningless: if they have the same name, they have the same value, and the other way around. Android does not "keep" one or "discard" one. @+id creates an identifier *if it doesn't exist yet.*
Romain Guy
My question was born because of a misunderstanding of R.java mechanism: I thought that R.java contains "pointers" to the View objects. Now I know that it is just an identifier container. Therefore, the @+id mechanism is completely logic now.
bodom_lx
+9  A: 

The @+id/foo syntax will add if the id doesn't exist or use the existing id.
When you findViewById, it will operate on the view on which you call the method.

So, if you have nested Views, your id will be unique for each view. e.g. View1 -> View2 both have foo. View1.findViewById(R.id.foo) will be different from View2.findViewById(R.id.foo)

edit: I guess the main thing to mention is that two layouts can't have the same id. For more information on the id constraint: http://d.android.com/guide/topics/ui/declaring-layout.html

Jim Schubert
The second point is especially important if you use includes, as re-using the same layout with include will often result in the same IDs being used in multiple branches of the View tree.
Daniel Lew
Does this mean that R.java acts only as a name container?What happens if I declare two buttons in two different xml files having the same id name and I try to retrieve it in an Activity?Edit: the link you just added makes me think that a Layout also acts as "namespace" for the ids declared inside it.
bodom_lx
+1 for a good point. I updated my answer with a link to the guide specifically mentioning this. I think it can be slightly confusing to a developer (especially a web developer) who has become accustomed to using unique ids for elements across an application, such as elements in a web page.
Jim Schubert
@bodom_lx, I don't think you could have, for instance, two files: main_layout.xml and secondary_layout.xml, both with `@+id/layout`. I haven't tried this, but I don't think your application will compile.
Jim Schubert
Thank you very much!
bodom_lx