Android:用 ConstraintLayout 写一个文章标题栏(性能优化:布局)
先不急着背概念。下面这个例子只做一件事:标题在顶部左右约束,带 16dp 内边距。跑通之后,再回头看「用 ConstraintLayout 写一个文章标题栏」会轻松很多。
示例代码
顶部注释不是装饰,标的是每个关键函数/类为什么存在。读代码时可以从那里入手。
<?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
友善交流,让讨论变得更有价值。