Android:用 ConstraintLayout 写一个文章标题栏(常用控件 TextView/Button/EditText)

有些知识点看十遍不如跑一遍。下面的代码就是为「用 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:显示文章标题
  • 约束属性:把标题固定在顶部并拉通宽度

结果不对时先看这里

复制代码时漏掉分号、缩进或导入,报错信息通常比代码本身更直接。

练习

  1. 先不看代码,写出你对「用 ConstraintLayout 写一个文章标题栏」执行过程的预测,再运行对照。
  2. 改掉 ConstraintLayout 的一行关键实现,观察报错信息,再恢复它。

先把这一小段改到能解释每一行,再考虑加功能;慢一点反而更快。