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:显示文章标题
  • 约束属性:把标题固定在顶部并拉通宽度

边界情况

一次改太多行,出错后不知道是哪一步引入的;改一行,跑一次。

接下来动手

  1. 把示例删到只剩最核心的几行,确认它还能跑;再逐行加回被删掉的部分。
  2. 把 ConstraintLayout 换成更小的版本,只保留当前示例需要的能力。

别急着收藏。关掉页面,自己重写一遍,能独立跑通才算真的会。