Difference between android:id, android:name and na

2019-04-04 13:29发布

问题:

Can someone clarify the difference between android:id, android:name and name tags in Android's XML files. They all seem to be ways to reference things.

For example, when I have a string array in the res/values/array.xml file I access using the name field in the defined array yet the Javadoc refers to this as the "ID".

android:id seems to be just used in Views ?

Am I missing something or would it not be simpler to have one tag?

回答1:

No, I don't believe you're missing anything. Although these fields are named differently, it's my understanding that they are both used to identify/reference resources. This specifically means GUI elements (views) in the case of android:id and static resources in the case of name.

To go into more depth, I believe the android:id attribute is assigned only to Views and classes that extend View. This is done so that the view can be programmatically accessed from your code using findViewById:

Button myButton = (Button) findViewById(R.id.whatever_id_assigned_to_view)

This is different from resources such as strings.xml or array.xml which are identified simply by name, such as a following example of what might be found in strings.xml:

<string name="string_name">Text Resource Here</string>

and is accessed using...

getResources().getText(R.string.string_name)

I imagine these are separated for organizational reasons. This way the generated Android resource file (R.java) contains the IDs specified for views in R.id, the string IDs contained in R.string, array IDs in R.array etc.