FrameLayout帧布局和GridLayout网格布局

FrameLayout(帧布局)和GridLayout(网格布局)也是Android开发会用到的布局,虽然不及LinearLayout和RelativeLayout使用频率高,但还是有必要get一下。

FrameLayout帧布局

与其它布局相比,帧布局比较简单,用法也比较单一。FrameLayout的属性很少就两个:

  • android:foreground 设置帧布局容器的前景图像

  • android:foregroundGravity 设置前景图像显示的位置

前景图像:永远处于帧布局最上面,直接面对用户的图像,就是不会被覆盖的图片。

下面写个示例体验一下帧布局的效果:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:foreground="@mipmap/ic_launcher"
 android:foregroundGravity="bottom|right">
 <TextView
 android:layout_width="240dp"
 android:layout_height="240dp"
 android:background="@color/teal_200"/>
 <TextView
 android:layout_width="160dp"
 android:layout_height="160dp"
 android:background="@color/purple_200"/>
 <TextView
 android:layout_width="80dp"
 android:layout_height="80dp"
 android:background="@color/teal_700"/>
</FrameLayout>

效果预览图:

FrameLayout

上图右下角是帧布局的前景图,而帧布局的子项自上而下的堆叠在一起。

GridLayout网格布局

GridLayout网格布局也很简单,用来实现类似格子类的效果特别方便,用到的属性如下:

  • android:orientation 排列方向

  • android:layout_gravity 对齐方式

  • android:columnCount="4" android:rowCount="4" 几行几列

  • android:layout_row="1" android:layout_column="2" 子项在几行几列,索引从零开始

  • android:layout_rowSpan="2" android:layout_columnSpan="1" 子项占几行几列

下面写个例子验证一下上面的属性:

<?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:orientation="vertical"
 android:rowCount="4"
 android:columnCount="4">
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="2行1列"
 android:textSize="18sp"
 android:layout_rowSpan="2"
 android:layout_gravity="fill"
 android:backgroundTint="@color/teal_700"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="1行2列"
 android:textSize="18sp"
 android:layout_columnSpan="2"
 android:layout_gravity="fill"
 android:backgroundTint="@color/teal_200"/>
 <Button
 android:text="2行2列"
 android:textSize="18sp"
 android:layout_rowSpan="2"
 android:layout_columnSpan="2"
 android:layout_gravity="fill"
 android:backgroundTint="@color/purple_200"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>
 <Button
 android:text="1.1"
 android:textSize="18sp"/>

</GridLayout>

效果预览图:

GridLayout

上面示例简单的展示了跨行跨列的效果。GridLayout 将容器切割为棋盘一样4行4列的网格,每个网格可以放置一个组件,添加到容器的组件从左向右自上而下依次放置。GridLayout最大的特点是放置的组件自动占据网格的整个区域,每个组件的大小相同。不能改变组件大小(除非组件内容撑开改变),只能改变组件之间的水平和垂直间隔。

若组件数超过网格设定的个数,则布局管理器会自动增加网格个数,原则是保持行数不变,增加列数来完成布局。当容器大小发生改变时,各组件的相对位置不变,大小会改变。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容