Android 4.0新组件:GridLayout详解

在Android 4.0(API 14)中提供了一个全新的组件GridLayout,它继承自Linearlayout,用于进行网格式的布局。

在某些方面,GridLayout与TableLayout和GridView有相似之处。他的强大之处在于可以指定每一个单元格“横跨”几个单元格或者“竖跨”几个单元格,这一点与html中<table>标签很类似。

GridLayout的几个重要属性:

rowCount:行数

columnCount:列数

GridLayout的子View将可以应用属性:

layout_rowSpan:纵向跨几个单元格

layout_columnSpan:横向跨几个单元格

同时,GridLayout的子View可以不指定layout_width和layout_height(类似于TableLayout)


使用GridLayout可以很方便的开发出类似计算器的页面,相比使用LinearLayout简化了代码、简化了嵌套层次、提高了性能,并且自适应性能更好。

示意图:

技术分享   

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="8dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="计算器" />

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="4"
        android:layout_margin="4dp">

        <Button android:text="C" />

        <Button android:text="Del" />

        <Button android:text="/" />

        <Button android:text="x" />

        <Button android:text="7" />

        <Button android:text="8" />

        <Button android:text="9" />

        <Button android:text="-" />

        <Button android:text="4" />

        <Button android:text="5" />

        <Button android:text="6" />

        <Button android:text="+" />

        <Button android:text="1" />

        <Button android:text="2" />

        <Button android:text="3" />

        <Button
            android:text="="
            android:layout_gravity="fill"
            android:layout_rowSpan="2" />

        <Button
            android:text="0"
            android:layout_gravity="fill"
            android:layout_columnSpan="2" />

        <Button android:text="." />

    </GridLayout>
</LinearLayout>


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。