Beginning Android
Using XML-Based Layouts
While it is technically possible to create and attach widgets to our activity purely through Java code, the way we did in Chapter 4, the mon approach is to use an XML-based layout file. Dynamic instantiation of widgets is reserved for plicated scenarios, where the widgets are not known pile-time (e g., populating a column of radio buttons based on data retrieved off the ).
With that in mind, it’s time to break out the XML and learn how to lay out Android activities that way.
What Is an XML-Based Layout?
As the name suggests, an XML-based layout is a specification of widgets’ relationships to each other—and to their containers (more on this in Chapter 7)—encoded in XML format. Specifically, Android considers XML-based layouts to be resources, and as such layout files are stored in the res/layout directory inside your Android project.
Each XML file contains a tree of elements specifying a layout of widgets and their containers that make up one view hierarchy. The attributes of the XML elements are properties, describing how a widget should look or how a container should behave. For example, if a Button element has an attribute value of android:textStyle = "bold", that means that the text appearing on the face of the button should be rendered in a boldface font style.
Android’s SDK ships with a tool (aapt) which uses the layouts. This tool should be automatically invoked by your Android tool chain (., Eclipse, Ant’s ). Of particular importance to you as a developer is that aapt generates the source file within your project, allowing you to access layouts and widgets within those layouts directly from your Java code.
Why Use XML-Based Layouts?
Most everything you do using XML layout files can be achieved through Java code. For example, you could use setTypeface() to have a button render its text in bold, instead of using a property in an XML layout. Since XML layouts are yet another file for yo
外文文献 来自淘豆网m.daumloan.com转载请标明出处.