Android開發(fā)學(xué)習(xí)教程(15)- Android布局之幀布局FrameLayout
2023-01-27 16:07 作者:ChatGPT云炬學(xué)長 | 我要投稿
—— If not me, who? If not now, when?
上一篇我們講了相對布局RelativeLayout的基本用法,這里來學(xué)習(xí)常用布局之幀布局FrameLayout的基本用法。
幀布局是什么
幀布局中的控件只能通過layout_gravity來控制控件的位置,如果不設(shè)置layout_gravity屬性所有控件都會(huì)按照添加順序一個(gè)一個(gè)的堆在幀布局的左上角。相同層級(jí)布局中 FrameLayout的效率也是最高的,占用內(nèi)存相對來說也是較小的(具體原因在后續(xù)篇章會(huì)詳細(xì)講)。
幀布局有什么用
通過layout_gravity控制控件在屏幕的位置。
幀布局怎么用
繼續(xù)基于上一篇的項(xiàng)目,我們新建一個(gè)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
=
"我是第一個(gè)子控件"
?/>
????
<
TextView
????????
android:layout_width
=
"wrap_content"
????????
android:layout_height
=
"wrap_content"
????????
android:layout_gravity
=
"center_horizontal"
????????
android:text
=
"我是第二個(gè)子控件"
?/>
????
<
TextView
????????
android:layout_width
=
"wrap_content"
????????
android:layout_height
=
"wrap_content"
????????
android:layout_gravity
=
"right"
????????
android:text
=
"我是第三個(gè)子控件"
?/>
????
<
TextView
????????
android:layout_width
=
"wrap_content"
????????
android:layout_height
=
"wrap_content"
????????
android:layout_marginTop
=
"40dp"
????????
android:text
=
"我是第四個(gè)子控件"
?/>
????
<
TextView
????????
android:layout_width
=
"wrap_content"
????????
android:layout_height
=
"wrap_content"
????????
android:layout_marginTop
=
"80dp"
????????
android:text
=
"我是第五個(gè)子控件"
?/>
</
FrameLayout
>
第一個(gè)控件
1
2
3
4
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:text
=
"我是第一個(gè)子控件"
?/>
沒有設(shè)置任何屬性,控件默認(rèn)顯示在FrameLayout左上角
第二個(gè)控件
1
2
3
4
5
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:layout_gravity
=
"center_horizontal"
????
android:text
=
"我是第二個(gè)子控件"
?/>
屬性android:layout_gravity=”center_horizontal”表示TextView控件位于FrameLayout的水平居中位置
第三個(gè)控件
1
2
3
4
5
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:layout_gravity
=
"right"
????
android:text
=
"我是第三個(gè)子控件"
?/>
屬性android:layout_gravity=” right “表示TextView控件位于FrameLayout的最右邊
第四個(gè)控件
1
2
3
4
5
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:layout_marginTop
=
"40dp"
????
android:text
=
"我是第四個(gè)子控件"
?/>
屬性android:layout_marginTop=”40dp”表示TextView控件距離FrameLayout頂部40dp,同理,第五個(gè)控件距離FrameLayout頂部80dp
源碼鏈接:https://yunjunet.cn/876764.html
標(biāo)簽: