Using XML-Based Layouts
While it is technically possible to create andattach widgets to your activity purely
through Java code, as we did in the preceding chapter, the more common approach is
to use an XML-based layout file. Dynamic instantiation of widgets is reserved for more
complicated scenarios, where the widgets are not known at compile time (e.g.,
populating a column of radio buttons based on data retrieved from the Internet).
With that in mind, it’s time to break out the XML and learn how to lay out Android activity
views 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 containers—encoded inXML format. Specifically, Android
considers XML-based layouts to be resources, andas such, layout files are stored in the
reslayoutdirectory inside your Android project.
Each XML file contains a tree of elements specifying a layout of widgets and containers
that make up one View. 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 ina boldface font style.
Android’s SDK ships with a tool (aapt) that uses the layouts. This tool should be
automatically invoked by your Android tool chain (e.g., Eclipse or Ant’s build.xml). Of
particular importance to you as a developer is that aaptgenerates the R.javasource file
within your project’s gendirectory, allowing you to access layouts and widgets within
those layouts directly from your Java code, aswill be demonstrated later in this chapter.
đang được dịch, vui lòng đợi..
