作者:刘昊昱
博客:http://blog.youkuaiyun.com/liuhaoyutz
在帧布局管理器中,每加入一个组件,都将创建一个空白的区域,通常称为一帧,这些帧会根据gravity属性执行自动对齐,默认情况下,帧布局从屏幕左上角(0,0)位置开始布局,多个组件层叠排序,后加入的组件覆盖先加入的组件。
下面看一个例子,该程序运行效果如下图所示:
主布局文件main.xml内容如下所示:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:foreground="@drawable/dog"
android:foregroundGravity="bottom|right"
>
<!-- 添加居中显示的红色背景的TextView,将显示在最下层 -->
<TextView android:text="红色背景的TextView"
android:id="@+id/textView1"
android:background="#FFFF0000"
android:layout_gravity="center"
android:layout_width="300px"
android:layout_height="300px"/>
<!-- 添加居中显示的橙色背景的TextView,将显示在中间层 -->
<TextView android:text="橙色背景的TextView"
android:id="@+id/textView2"
android:layout_width="200px"
android:layout_height="200px"
android:background="#FFFF6600"
android:layout_gravity="center"
/>
<!-- 添加居中显示的黄色背景的TextView,将显示在最上层 -->
<TextView android:text="黄色背景的TextView"
android:id="@+id/textView3"
android:layout_width="100px"
android:layout_height="100px"
android:background="#FFFFEE00"
android:layout_gravity="center"
/>
</FrameLayout>
从上面的代码和运行效果可以看出,加入到FrameLayout中的三个组件层叠放置,后加入的UI组件覆盖在先加入的UI组件上方。
帧布局经常应用在游戏开发中,用于显示自定义的视图,达到分层的效果。