Android开发从入门到放弃(7)使用GridLayout

来源:互联网 发布:王路 知乎 编辑:程序博客网 时间:2024/05/22 12:58

本篇博客简单介绍一下Android开发中的GridLayout。GridLayout跟上一篇的主题TableLayout在功能上十分相似,都是以表格地形式来布局,但在具体的用法上有些不同。

创建表格的方式

GridLayout在创建表格时就已经指定了行数和列数。通过GridLayout的columnCount属性设置列数,通过rowCount指定行数。而TableLayout是通过手动添加TableRow的形式来指定行的,TableRow中的每个View控件都算一列。

指定控件的行和列

默认情况下,GridLayout中的控件会自动生成行索引和列索引。假设有一个3*4的GridLayout,中间有10个元素,那么这十个元素的行号和列号用(行号,列号)的形式来表示的话分别是:(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3)(2,0) (2,1)。也就是先按顺序占满一行,然后继续占满下一行。
但是,可以手动地来设置行和列。View控件的layout_row属性来决定当前控件位于第几行,layout_column属性来决定当前控件位于第几列。
需要注意的是,一旦某个控件手动地指定了行或列,下面的所有控件也都需要手动指定,否则最后的结果将会拆强人意。

指定控件横跨几列

默认情况下一个View控件占用1列,但可以通过layout_columnSpan属性来指定当前控件横跨几列。

一个使用GridLayout的例子

上一篇博客通过TableLayout实现的那个界面,下面的这个例子我们来通过GridLayout再实现一次

<?xml version="1.0" encoding="utf-8"?><GridLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_grid_layout"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:columnCount="4"    android:rowCount="2"    tools:context="com.example.zdk.relativelayoutdemo.GridLayoutActivity">    <TextView        android:text="username"/>    <EditText        android:hint="input your username"        android:layout_columnSpan="3"        android:layout_columnWeight="1"/>    <Button        android:layout_column="2"        android:layout_row="1"        android:text="Cancel" />    <Button android:text="OK"        android:layout_column="3"        android:layout_row="1"        /></GridLayout>
0 0
原创粉丝点击