This page in the Android documentation defines an element id as follows:
<TextView android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
However this page defines it as:
<EditText id="text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_hei开发者_Python百科ght="fill_parent"
android:textColor="@color/opaque_red"
android:text="Hello, World!" />
I thought I had a decent understanding of what was going on until I saw this second example. In the first case, you need the + character so that id 'label' is added to the R file, correct? In the second case, would the EditText's id not be added to the R file because it does not contain the + character?
Also, the second example does not include the android namespace on the id. Does having or not having the Android namespace affect whether that id will be added to the R file?
Thanks for any clarification.
This format without the android: namespace
id="text"
is from an earlier version of the Android SDK.
You are correct in your initial assessment. It's worth noting that the second id tag
<EditText id="text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="Hello, World!" />
Is missing the android:
namespace so it actually isn't an android xml tag. The first one is an example of how to add that view's id to the R file so you can access it in your code. To be honest, I'm not sure what the purpose of the id in the second example is*, but I know that android wouldn't know what to do with it. The first one is the correct syntax.
*This is just speculation, but I'm willing to bet it was a typo somebody didn't notice or didn't care to fix because they were trying to illustrate something else.
The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:
android:id="@android:id/empty"
Taken from Declaring Layout | Android Developers in the ID section.
However, in your second example there is no @android:id/
provided before the id text
so to be brutally honest, I have never seen that notation before and wonder if that could be a typo on the author's part.
The second example is wrong. The attribute is always android:id and the value should be either @+id/myId (to create a new id called "myId") or @id/myId (to use an already defined id called "myId".) Using @android:id/theId lets you use ids defined by the android platform.
精彩评论