课程进度 32% · 第4/11章第4/11章 · 标签 1/2
— 1 —
布局 XML 基础
Android 使用 XML 定义界面布局。常用布局容器包括 LinearLayout(线性布局)、RelativeLayout(相对布局)和 ConstraintLayout(约束布局)。
xml
1
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2
android:layout_width="match_parent"
3
android:layout_height="match_parent"
4
android:orientation="vertical">
5
6
<TextView
7
android:id="@+id/tv_hello"
8
android:layout_width="wrap_content"
9
android:layout_height="wrap_content"
10
android:text="Hello Android"
11
android:textSize="18sp" />
12
13
<Button
14
android:id="@+id/btn_click"
15
android:layout_width="wrap_content"
16
android:layout_height="wrap_content"
17
android:text="点击我" />
18
19
</LinearLayout>
📖match_parent 填充父容器,wrap_content 包裹内容,dp/sp 是屏幕密度无关的单位
— 2 —
ConstraintLayout 约束布局
ConstraintLayout 是官方推荐的布局方式,通过约束关系定位子视图,可大幅减少布局嵌套深度。
xml
1
<androidx.constraintlayout.widget.ConstraintLayout
2
xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
android:layout_width="match_parent"
5
android:layout_height="match_parent">
6
7
<Button
8
android:id="@+id/btn"
9
android:layout_width="wrap_content"
10
android:layout_height="wrap_content"
11
android:text="按钮"
12
app:layout_constraintTop_toTopOf="parent"
13
app:layout_constraintStart_toStartOf="parent"
14
app:layout_constraintEnd_toEndOf="parent"
15
app:layout_constraintBottom_toBottomOf="parent" />
16
17
</androidx.constraintlayout.widget.ConstraintLayout>
◆
常用约束属性
xml
1
app:layout_constraintTop_toTopOf="parent"
2
app:layout_constraintBottom_toBottomOf="parent"
3
app:layout_constraintStart_toStartOf="parent"
4
app:layout_constraintEnd_toEndOf="parent"
5
app:layout_constraintLeft_toLeftOf="parent"
6
app:layout_constraintRight_toRightOf="parent"
7
app:layout_constraintHorizontal_bias="0.5"
8
app:layout_constraintVertical_bias="0.3"