Android: new layout widgets: space and gridlayout

Source: Internet
Author: User
Document directory
  • Gridlayout
  • Getting started
  • Sizes, margins and alignment/gravity
  • Flexibility
  • Emulating features from other layouts
  • The phases of the layout operation
  • Conclusion
10 November 2011

Http://android-developers.blogspot.com/2011/11/new-layout-widgets-space-and-gridlayout.html

New layout widgets: space and gridlayout

[This post is by Philip Milne, who is part of the android Framework Team.-Tim Bray]

Ice cream sandwich (ICS) Sports two new widgets that have been designed to support the richer user interfaces made possible by larger displays:
Space and
Gridlayout.

The most commonly used class for layout in Android is
Linearlayout, which allows its children to be aligned in the usual ways: along either the horizontal or vertical axes. it's often possible to take a complicated layout and break it down into a set of nested linear layouts and, provided this nesting doesn't
Get too deep, this is still a good choice for processing simple layouts.

A number of posts and articles (e.g.
Android layout tricks #1,
Flattening the stack) have highlighted drawbacks of nested layouts; which fall into three basic categories:

  • Inability to control alignment along both axes simultaneously

  • Performance problems in hierarchies that are too deep

  • Unsuitability for design tools that support free-form editing

A simple example of the first problem is the following form:

As the font and the text of the "email address" label change, we want the label to remain aligned with
BaselineOf the component to its right, and aligned withRightEdge of the label below it. It's not possible to do this with nested linearlayouts because the label needs to be aligned with other components both horizontally and vertically.

These problems aren't new to Android, or UI toolkits in general, but we 've used them to drive our work in enriching platform support for flatter hierarchies.

Gridlayout

To provide better support for layouts like these we have added a new layout to the android framework: gridlayout, which can be used to solve the above problems by dividing the container's real estate into rows and columns:

Now the "email address" label can belong both toRowThat isBaseline-Aligned, and
ColumnThat isRight-Aligned.

Gridlayout uses a grid of Infinitely-thin lines to separate its drawing area:
Rows,Columns, AndCells. It supports both row and column
Spanning, Which together allow a widget to occupy a rectangular range of cells that are next to each other. We'll use the words
Row,Column, AndCellIn the text below as shorthand
Row Group,Column GroupAndCell GroupRespectively, where groups have one or more contiguous elements.

Similarities with linearlayout

Wherever possible, gridlayout uses the same conventions as linearlayout for all its xml api-so it shocould be easy to start using gridlayout if you 've already used linearlayout. in fact, the APIs are so similar that changing a tag name from linearlayout
To gridlayout in an XML file that uses linearlayout will often produce a similar UI without requiring any other changes. when it doesn't, you'll still generally end up with a good starting point for a two-dimen1_layout.

Getting started

Two examples in the samples area of the android 4.0 SDK show typical use of the programmatic and XML APIs respectively:

  • Samples/apidemos/src/COM/example/Android/APIs/View/gridlayout0.java

  • Samples/apidemos/RES/layout/grid_layout_1.xml

[Both examples produce the same UI.]

Here's a slightly simpler version of the above XML layout.

<?xml version="1.0" encoding="utf-8"?><GridLayout        xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:useDefaultMargins="true"        android:alignmentMode="alignBounds"        android:columnOrderPreserved="false"        android:columnCount="4"        >    <TextView            android:text="Email setup"            android:textSize="32dip"            android:layout_columnSpan="4"            android:layout_gravity="center_horizontal"            />    <TextView            android:text="You can configure email in just a few steps:"            android:textSize="16dip"            android:layout_columnSpan="4"            android:layout_gravity="left"            />    <TextView            android:text="Email address:"            android:layout_gravity="right"            />    <EditText            android:ems="10"            />    <TextView            android:text="Password:"            android:layout_column="0"            android:layout_gravity="right"            />    <EditText            android:ems="8"            />    <Space            android:layout_row="4"            android:layout_column="0"            android:layout_columnSpan="3"            android:layout_gravity="fill"            />    <Button            android:text="Next"            android:layout_row="5"            android:layout_column="3"            /></GridLayout>

The first difference you'll notice in these examples is the absence of the wrap_content and match_parent constants that normally adorn Android layout resources. you don't normally need to use these with gridlayout, for reasons that are described in the API
Doc
Gridlayout. layoutparams.

Row and column indices

The second thing you may notice in the XML resources is that widgets don't always explicitly define which cells they are to be placed in. each widget's layout parameters have row and column indices that together define where the widget shocould be placed
When either or both of these values are not specified, gridlayout supplies default values rather than throwing an exception.

Automatic index allocation

As children are added to a gridlayout, it maintains a cursor position and a "high-water mark" that it uses to place widgets in cells that don't yet have anything in them.

When gridlayout's
Orientation property ishorizontalAnd
Columncount has been set (to 8 in this example) the high-water mark (shown above in
Red) is maintained as a separate height value for each column. When indices need to be created, gridlayout first determines the size of the cell group (by looking at

Rowspan and
Columnspan parameters of the new widget) And then, starting at the cursor, goes through the available locations from: left to right, top to bottom, so as to find the row and column indices of the first location that's free.

When gridlayout's orientation isvertical, All of the same principles apply, role t that the roles of the horizontal and vertical axes are exchanged.

If you want multiple views to be placed in the same cell, you have to define the indices explicitly, as the default allocation procedure above is designed to place widgets in separate cells.

Sizes, margins and alignment/gravity

In gridlayout, specifying sizes and margins is done just as with a linearlayout. Alignment/gravity also works just like gravity in linearlayout and uses the same constants:
Left,
Top,

Right,
Bottom,
Center_horizontal,
Center_vertical,
Center,
Fill_horizontal,
Fill_vertical and
Fill.

Flexibility

Unlike most grids in other toolkits, gridlayout does not associate data with rows or columns. instead, everything to do with alignment and flexibility is associated with the components themselves. gridlayout departs from the norm here to provide a more general
System that allows subtle relationships between ancestors in deeply nested layouts to be accommodated in a single layout configuration.

The flexibility of columns is inferred from the gravity of the components inside the column. if every component defines a gravity, the column is taken as flexible, otherwise the column is considered inflexible. full details are in gridlayout's
API docs.

Emulating features from other layouts

Gridlayout does not ineffecate all of the features of every layout in the Android platform but it has a rich enough feature set that idiomatic use of other layouts can normally be emulated from inside a single gridlayout.

Although
Linearlayout can be considered a special case of a gridlayout, for the degenerate case when a set of views are aligned in a single row or column, linearlayout is the better choice when this is all that is required as it clarifies the purpose of the container
And may have some (relatively small) performance advantages.

Tablelayout tolerations are normally straightforward to accommodate, as gridlayout supports both row and column spanning.
Tablerows can be removed, as they are not required by gridlayout. For the same UI, A gridlayout will generally be faster and take less memory than a tablelayout.

Simple
Relativelayout tolerations can be written as grids simply by grouping the views that are related to each other into rows and columns. unlike conventional grids, gridlayout uses a constraints solver to do the heavy lifting of the layout operation. by
Using gridlayout's
Roworderpreserved and
Columnorderpreserved properties it's possible to free gridlayout from the confines of traditional grid systems and support the majority of relativelayout deployments-even ones that require grid lines to pass over each other as children change size.

Simple
Framelayout deployments can be accommodated within the cells of a gridlayout because a single cell can contain in multiple views. to switch between two views, place them both in the same cell and use the visibility constant
Gone to switch from one to the other from code. As with the linearlayout case above, if all you need is the functionality described above, framelayout is the better choice and
May have some small performance advantages.

One key feature that gridlayout lacks is the ability to distribute excess space between rows or columns in specified proportions-a feature that linearlayout provides by supporting the principle

Weight. This omission and possible ways around und it are discussed in gridlayout's API docs.

The phases of the layout operation

It's useful to distinguish the allocation phase for cell indices discussed abve from the layout operation itself. normally the phase that allocates indices happens once, if at all, when a UI is initialized. the index-allocation phase only applies when indices
Have been left unspecified, and is responsible for ensuring that all views have a defined set of cells in which they are to be placed at layout time.

The layout operation happens after this and is recalculated each time a view changes size. gridlayout measures the size of each child during the layout operation so it can calcuate the heights and widths of the rows and columns in the grid. the layout phase
Completes by using gravity to place each of the components in its cell.

Although index allocation normally only happens once, gridlayout is technically a dynamic layout, meaning that if you change its orientation property or add or remove children after components have been laid out, gridlayout will repeat the above procedure
To reallocate indices in a way that is right for the new configuration.

From a performance standpoint, it is worth knowing that the gridlayout implementation has been optimized for the common case, when initialization happens once and layout happens frequently. as a result, the initialization step sets up internal data structures
So that the layout operation can complete quickly and without allocating memory. put another way, changes either to gridlayout's orientation or the number of children it has are much more expensive than ordinary layout operation.

Conclusion

Gridlayout's feature set inconfigurates much of the functionality of the android Framework's existing general-purpose layouts: linearlayout, framelayout, tablelayout and relativelayout. as such, it provides a way to replace into deeply nested view hierarchies
With a single highly optimized layout implementation.

If you are starting a UI from scratch and are not familiar with Android layouts, use a gridlayout-it supports most of the features of the other layouts and has a simpler and more general api than either tablelayout or relativelayout.

We anticipate that the combination of framelayout, linearlayout and gridlayout together will provide a feature set that's rich enough to allow most layout problems to be solved without writing layout code by hand. it's worth spending some time deciding which
Of these layouts is right for the top of your tree; a good choice will minimize the need for intermediate containers and result in a user interface that is faster and uses less memory.

Posted bytim brayat3: 00
PMLabels: User Interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.