Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
When we looked at an example of the RelativeLayout, we gave one of the controls a name with an android:id attribute. Here is the line of code from the main.xml file:
android:id=“@+id/centertext”
The @ sign in the ID is a signal to the XML parser how to deal with the ID string. The + indicates that this is an ID the user has created; it is not part of the Android framework namespace. You can find further clarification on creating IDs at http://developer.android.com/guide/topics/ui/declaring-layout.html.
The android:id attribute was important to the RelativeLayout, but it is also important if the programmer wants to identify components from the XML layout file in the application’s Java code. For example, suppose we write an application with a text field where the user would enter her name. The programmer would need a way to identify that particular text field to extract the entered name to do something with it. There must be a way to link a component from the static design of the screen during development (the XML file) to the application at run-time (the Java code). If we think in terms of the MVC paradigm, we must connect the view to the control. In the Java code, we declare and assign an instance of an object matching the class of the element in the XML. In the case we are describing, it would be an EditText control. The assignment step uses the ID from the XML file to make the connection. We will see examples of this as soon as we begin coding an application, but we bring it up here because we are in the middle of discussing layouts and the main.xml file.
It is a good idea for reasons that will become apparent soon to put an android:id attribute on your layouts. For example, you could identify the lowest level layout, the one represented with the first opening tag, as “base.” When we added two TableLayouts to the underlying LinearLayout, the LinearLayout could be IDed as “base,” the first TableLayout as level2a or table_1. Do whatever you think is appropriate.