0%

Android 自适应布局

Android通过LinearLayout + RelativeLayout实现自适应布局

自适应布局要求切换不同大小的屏幕时,布局中控件所占区域的位置和比例不变

RelativeLayout可以控制控件相对位置,但无法指定控件所占空间比例,单RelativeLayout布局无法应对屏幕大小变化的情况

LinearLayout可以对其中的子控件指定layout_weightlayout_height属性,LinearLayout和RelativeLayout相互嵌套的方式可以完成自适应界面

例:上下结构(左右同理)

将屏幕分为上下或左右结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 指定垂直布局 -->
<!-- 需要指定子控件高度为0dp,否则layout_weight不生效 -->

<!-- 上半 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</RelativeLayout>

<!-- 下半 -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</RelativeLayout>
</LinearLayout>

例:嵌套界面实现底部Banner

在界面下方居中处,放置banner图片及退出按钮

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<!-- 上占位空白 -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.85"
android:visibility="invisible" />

<!-- Banner区 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.13"
android:orientation="horizontal" >

<!-- 左占位空白 -->
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.05"
android:visibility="invisible" />

<!-- Banner区 -->
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:background="#FFBDBDBD">

<!-- 模拟Banner退出按钮 -->
<FrameLayout
android:layout_width="15dp"
android:layout_height="15dp"
android:background="#FF0000"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp" />

<!-- Banner图片 -->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
</RelativeLayout>

<!-- 右边占位空白 -->
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.05"
android:visibility="invisible" />
</LinearLayout>

<!-- 下占位空白 -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.02"
android:visibility="invisible" />

</LinearLayout>