2025.5.19
学习内容
RelativeLayout 学习:RelativeLayout 是相对布局,子视图通过相对位置进行排列。可通过android:layout_above、android:layout_below、android:layout_toLeftOf、android:layout_toRightOf等属性设置子视图之间的相对位置关系。例如,将一个 Button 放在 TextView 的下方:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view"
android:text="文本"
android:textSize="20sp"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:text="按钮"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text_view"/>
ConstraintLayout 学习:ConstraintLayout 是一种灵活的布局方式,通过约束条件来定位子视图。在布局文件中使用<androidx.constraintlayout.widget.ConstraintLayout>作为根布局,子视图通过app:layout_constraintLeft_toLeftOf、app:layout_constraintTop_toTopOf等属性设置约束关系。例如,将 Button 水平居中且位于 TextView 下方:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view"
android:text="文本"
android:textSize="20sp"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="@+id/button"
android:text="按钮"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/text_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
收获
学会了 RelativeLayout 和 ConstraintLayout 两种布局方式,对比发现 ConstraintLayout 在复杂布局时更具优势,能更灵活地实现各种布局效果。通过练习不同布局方式,对 Android 的界面设计有了更多的选择和思路。

浙公网安备 33010602011771号