Step

The Art of Layout

The provided note_edit.xml layout file is the most sophisticated one in the application we will be building, but that doesn't mean it is even close to the kind of sophistication you will be likely to want in real Android applications.

Creating a good UI is part art and part science, and the rest is work. Mastery ofDeclaring Layout is an essential part of creating a good looking Android application.

Take a look at the Hello Views for some example layouts and how to use them. The ApiDemos sample project is also a great resource from which to learn how to create different layouts.

Open the file note edit.xml that has been provided and take a look at it. This is the UI code for the Note Editor.

This is the most sophisticated UI we have dealt with yet. The file is given to you to avoid problems that may sneak in when typing the code. (The XML is very strict about case sensitivity and structure, mistakes in these are the usual cause of problems with layout.)

There is a new parameter used here that we haven't seen before: android:layout weight (in this case set to use the value 1 in each case).

layout weight is used in LinearLayouts to assign "importance" to Views within the layout. All Views have a default layout weight of zero, meaning they take up only as much room on the screen as they need to be displayed. Assigning a value higher than zero will split up the rest of the available space in the parent View, according to the value of each

View's layout weight and its ratio to the overall layout weight specified in the current layout for this and other View elements.

To give an example: let's say we have a text label and two text edit elements in a horizontal row. The label has no layout weight specified, so it takes up the minimum space required to render. If the layout weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important). If the first one has a layout weight of 1 and the second has a layout weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).

This layout also demonstrates how to nest multiple layouts inside each other to achieve a more complex and pleasant layout. In this example, a horizontal linear layout is nested inside the vertical one to allow the title label and text field to be alongside each other, horizontally.

0 0

Post a comment