Android:用 ConstraintLayout 写一个文章标题栏(用无障碍语义优化列表)
有些知识点看十遍不如跑一遍。下面的代码就是为「用 ConstraintLayout 写一个文章标题栏」准备的,跑完你会看到:标题在顶部左右约束,带 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>代码拆解
不必按顺序背 API,先盯住每个关键类/函数负责的那一段数据流。
ConstraintLayout:根布局容器TextView:显示文章标题约束属性:把标题固定在顶部并拉通宽度
边界情况
只测平均情况,不测边界和长尾,真实流量一上来就露馅。
接下来动手
- 把示例删到只剩最核心的几行,确认它还能跑;再逐行加回被删掉的部分。
- 把
ConstraintLayout换成更小的版本,只保留当前示例需要的能力。
先把这一小段改到能解释每一行,再考虑加功能;慢一点反而更快。
评论 0
友善交流,让讨论变得更有价值。