Android:用 ConstraintLayout 写一个文章标题栏(用 TextInputLayout 校验登录表单)
这段代码不为演示框架,只为把「用 ConstraintLayout 写一个文章标题栏」写成一个能跑通的最小现场。它会标题在顶部左右约束,带 16dp 内边距。
它解决什么问题
标题在顶部左右约束,带 16dp 内边距。重点不是记住代码,而是看清输入、处理和输出之间的对应关系。
示例代码
代码不长,关键类/函数的职责已经写在顶部注释里。先原样跑一遍,再往下看拆解。
<?xml version="1.0" encoding="utf-8"?>
<!--
这段布局要解决的问题:标题在顶部左右约束,带 16dp 内边距
关键控件:
- ConstraintLayout:根布局容器
- 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"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="最新文章"
android:textSize="22sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>代码为什么这样写
ConstraintLayout:根布局容器TextView:显示文章标题约束属性:把标题固定在顶部并拉通宽度
结果不对时先看这里
复制代码时漏掉分号、缩进或导入,报错信息通常比代码本身更直接。
练习
- 先不看代码,写出你对「用 ConstraintLayout 写一个文章标题栏」执行过程的预测,再运行对照。
- 改掉
ConstraintLayout的一行关键实现,观察报错信息,再恢复它。
能用自己的话讲清楚每个关键类/函数为什么存在,这段示例才算消化了。
评论 0
友善交流,让讨论变得更有价值。