We all know that when generating an id for Androi开发者_开发百科d 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?
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
I tried a simple Hello World application with the following xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="text1"
/>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="text2"
/>
</LinearLayout>
Both my textviews have the same id. It compiles fine, runs fine, renders both the TextViews, and when i do a findViewByid() the first one gets found and all my function calls like setText are applied to it. Ideally, the AAPT should catch this but apparently it doesn't. It wont break something terribly unless the programmer relies on the id's. So its kind of like saying: if you are dumb enough to write such a code then you deserve to crash.
The AAPT won't care too much about it. For it, this is like a simple extension of Views with no explicit ids provided by the programmer.
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.
精彩评论