网格布局由GridLayout所代表,它是Android 4.0 新增的布局管理器,因此需要在Android 4.0之后的版本中才能使用此布局管理器。
GridLayout的作用类似HTML中的table标签,它把整个容器rows * columns个网格,每个网格可以放置一个组件。除此之外,也可以设置一个组件横跨多少列,一个组件横跨多少行。
为了控制GridLayout布局容器中各个子组件的布局分布,GridLayout提供一个内部类:GridLayout.LayoutParams,该类提供了大量的XML属性来控制GridLayout布局容器中子组件的布局分布。下面为其常用的XML属性相关方法。
android:layout_column 设置该子组件在GridLayout的第几列
android:layout_columnSpan 设置该子组件在GridLayout横向上跨几列
android:layout_gravity 设置该子组件采用何种方式占据该网格
android:layout_row 设置该子组件在GridLayout的第几行
android:layout_rowSpan 设置该子组件在GridLayout纵向上跨几行。
实例代码:
<?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:rowCount="6"
android:columnCount="4"
android:id="@+id/root">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:textSize="40sp"
android:layout_marginLeft="2pt"
android:layout_marginRight="2pt"
android:padding="3pt"
android:background="#eee"
android:textColor="#000"
android:text="0"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_columnSpan="4"
android:text="清除"/>
<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="-"/>
<Button
android:text="."/>
<Button
android:text="0"/>
<Button
android:text="="/>
<Button
android:text="+"/>
</GridLayout>
运行结果:
看到的朋友麻烦你们给我解释下为什么”/”,”*”,”-“,”+”这一列显示不完全。
谢谢