Android开发学习教程(15)- Android布局之帧布局FrameLayout
2023-01-27 16:07 作者:ChatGPT云炬学长 | 我要投稿
—— If not me, who? If not now, when?
上一篇我们讲了相对布局RelativeLayout的基本用法,这里来学习常用布局之帧布局FrameLayout的基本用法。
帧布局是什么
帧布局中的控件只能通过layout_gravity来控制控件的位置,如果不设置layout_gravity属性所有控件都会按照添加顺序一个一个的堆在帧布局的左上角。相同层级布局中 FrameLayout的效率也是最高的,占用内存相对来说也是较小的(具体原因在后续篇章会详细讲)。
帧布局有什么用
通过layout_gravity控制控件在屏幕的位置。
帧布局怎么用
继续基于上一篇的项目,我们新建一个FrameLayout:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?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"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是第一个子控件" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="我是第二个子控件" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="我是第三个子控件" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="我是第四个子控件" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="80dp" android:text="我是第五个子控件" /></FrameLayout>第一个控件
1
2
3
4
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是第一个子控件" />没有设置任何属性,控件默认显示在FrameLayout左上角
第二个控件
1
2
3
4
5
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="我是第二个子控件" />属性android:layout_gravity=”center_horizontal”表示TextView控件位于FrameLayout的水平居中位置
第三个控件
1
2
3
4
5
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="我是第三个子控件" />属性android:layout_gravity=” right “表示TextView控件位于FrameLayout的最右边
第四个控件
1
2
3
4
5
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="我是第四个子控件" />属性android:layout_marginTop=”40dp”表示TextView控件距离FrameLayout顶部40dp,同理,第五个控件距离FrameLayout顶部80dp
源码链接:https://yunjunet.cn/876764.html

