Defining views and layouts through XML resources

As we have noted in several earlier sections, views and layout can be, and often are, defined in XML rather than in Java code. Defining views and layout as resources in this way makes them easier to work with, decoupled from the code, and in some cases reusable in different contexts.

View resource files are placed in the res/layout source directory. The root of these XML files is usually one of the ViewGroup layout subclasses we have already discussed: RelativeLayout, LinearLayout, FrameLayout, and so on. Within these root elements are child XML elements that represent the view/layout tree.

An important thing to understand here is that resources in the res/layout directory don't have to be layouts. You can define a single TextView in a layout file the same way you might define an entire tree starting from an AbsoluteLayout. Yes, this makes the layout name and path potentially confusing, but that is how it is set up. (It might make more sense to have separate res/layout and res/view directories, but that might be confusing too, so just keep in mind that res/layout is useful for more than layout.)

You can have as many XML layout/view files as needed, all defined in the res/layout directory. Each View is then referenced in code based on the type and ID. Our layout file for the ReviewDetail screen, review_detail.xml, which is shown in listing 3.7, is referenced in the Activity code as R.layout.review_detail—which is a pointer to the RelativeLayout parent View object in the file.

0 0

Post a comment