Android 9 Development Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

There's more...

First, let's see more similarities between the layouts. Both layouts have the ability to stretch columns to use the remaining screen space. For TableLayout, add the following attribute to the XML declaration:

android:stretchColumns="1" 

The stretchColumns attribute specifies the (zero-based) index of the columns to stretch (android:shrinkColumns is a zero-based index of columns that can shrink, so the table can fit the screen).

To achieve the same effect with GridLayout, add the following attribute to all the Views in the B column (textView2, textView5, and textView8):

android:layout_columnWeight="1" 
All cells in a given column must define the weight or it will not stretch.

Now, let's look at some of the differences, as this is really the key to determining which layout to use for a given task. The first item to note is how the columns and rows are actually defined. In TableLayout, the rows are specifically defined, using TableRow. (Android will determine the number of columns in the table based on the row with the most cells.) Use the android:layoutColumn attribute when defining the View to specify the column.

In contrast, with GridLayout, the row and column counts are specified when defining the table (using columnCount and rowCount as shown previously).

In the preceding example, we just added TextView objects to GridLayout and let the system position them automatically. We can alter this behavior by specifying the row and column position when defining the View, such as the following:

android:layout_row="2" 
android:layout_column="2" 
Android automatically increments the cell counter after adding each View, so the next View should also specify the row and column, otherwise, you may not get the intended result.

Like LinearLayout, shown in the Using LinearLayout recipe, GridLayout also offers the orientation attribute of supporting both horizontal (the default) and vertical. The orientation determines how the cells are placed. (Horizontal fills the columns first, then moves down to the next row. Vertical fills the first column on each row, then moves to the next column.)