版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/txksnail/article/details/83151767
简介
帧布局或叫层布局,从屏幕左上角按照层次堆叠方式布局,后面的控件覆盖前面的控件,核心就是视图的层叠。类似于图层,这种视图的叠加思路在开发中处处可见。
重要属性
- 子View使用的属性
- android:layout_gravity
调整子View是父布局中的显示位置。常用属性值有center、center_vertical、center_horizontal、top、bottom、left、right等,可以同时取多个,通过"|"进行拼接
FrameLayout默认都是视图在左上角进行叠加,通过这个参数我们可以调整特定子view的在父布局中的显示位置
示例
- 默认的叠加效果
xml
<?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:background="#00FF78">
<TextView
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#aaaaaa" />
<TextView
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#FF0000" />
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#00FF00" />
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:background="#0000FF" />
</FrameLayout>
- 效果2
使用layout_gravity实现相对布局的效果
xml
<?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:background="#00FF78">
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:layout_gravity="top"//对齐父控件顶部
android:background="#0000FF" />
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:layout_gravity="right"//对齐父控件右边
android:background="#0000FF" />
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:layout_gravity="center"//父控件中居中
android:background="#0000FF" />
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:layout_gravity="bottom"//对齐父控件底部
android:background="#0000FF" />
<TextView
android:layout_width="49dp"
android:layout_height="54dp"
android:layout_gravity="right|bottom"//对齐父控件底部和右边
android:background="#0000FF" />
</FrameLayout>
拓展
FrameLayout中某个子View显示到最上面
FrameLayout提供了一个方法
public void bringChildToFront(View child)
只要指定子View就可以将子View显示在FrameLayout最上面,比如层叠了5个View,想把第三个显示出来就可以使用这个方法