Toolbar:本质,Android 应用中的工具栏

作者: IT Sectr 发布日期: 2026-02-23 阅读时间: 12 分钟

Toolbar(工具栏)——取代 ActionBar 的 Android 组件,显示屏幕标题、导航元素和操作。Toolbar 属于 Material Design Library,完全可定制:从标准标题到自定义视图和动画图标。有关该组件的更多信息,请阅读 Material Design 3 规范

要点

  • Toolbar——可定制的 Android 工具栏,继承自 Material Design 的 ActionBar
  • ActionBar——Android 5.0 之前存在的系统栏,已被 Toolbar 取代
  • Material 3——Top App Bar 有三种变体:Center、Small、Medium、Large
  • Menu——带有 action items 的 XML 菜单,通过 onCreateOptionsMenu 集成到 Toolbar
  • 定制——标题、徽标、导航图标、自定义视图和动画

什么是 Toolbar?

Toolbar——来自 Material Design 库(androidx.appcompat.widget.Toolbar)的 Android 组件,为应用屏幕提供灵活的工具栏。Toolbar 取代了过时的 ActionBar,让开发人员完全控制外观和行为。它可以放置在布局的任何位置,拥有自定义子视图,可以动画化并适应不同的屏幕尺寸。

Material Design 3(2026)定义了 Top App Bar——Toolbar 的演变——有四种变体:Small(紧凑型,48 dp)、Center-aligned(标题居中)、Medium(增大标题,112 dp)和 Large(大标题,168 dp)。每种变体在滚动时有自己的行为:Small 保持固定,Medium 和 Large 在内容向上滚动时收缩为 Small。

Toolbar 显示三个关键区域:导航图标(左侧,通常是"汉堡菜单"或"返回"箭头)、屏幕标题(居中或左侧)和 action items(右侧——操作图标,溢出菜单)。Toolbar 可以包含徽标、副标题、自定义 View(搜索视图、开关)以及与 CoordinatorLayout 配合使用的动画 CollapsingToolbarLayout。

ActionBar:历史与演变

ActionBar——Android 系统栏,出现在 Android 3.0(API 11)中,取代了过时的 Title Bar。ActionBar 与 Activity 紧密绑定,在屏幕顶部有固定位置,定制能力有限。随着 Android 5.0(Lollipop,2014)和 AppCompat 库的发布,Google 推出了 Toolbar 作为灵活的替代品。

ActionBar 的主要缺点已由 Toolbar 解决:固定位置(仅在顶部)、无法动画化、自定义视图困难、与 CoordinatorLayout 和 CollapsingToolbarLayout 的问题。Google 于 2015 年正式宣布 ActionBar 已弃用(deprecated),并推荐所有新项目使用 Toolbar。从 Android 12(2021)开始,ActionBar 在新 Material 3 主题中默认禁用。

特性ActionBarToolbar
位置固定顶部布局中任意位置
定制有限(颜色、背景)完全(视图、样式、动画)
折叠不支持CollapsingToolbarLayout
动画仅系统任意(ObjectAnimator、Transition)
Material 3不支持Small / Medium / Large App Bar

在 Android 中设置 Toolbar

使用 Toolbar 需要:(1)设置没有 ActionBar 的主题(Theme.Material3.NoActionBar 或 Theme.AppCompat.NoActionBar),(2)在 XML 布局中添加 Toolbar,(3)通过 setSupportActionBar 将其设置为 ActionBar。之后 Toolbar 获得 ActionBar 的所有功能:处理 Menu、导航图标、来自 AndroidManifest 的标题。

xml
<!-- 带有 Toolbar 的 activity_main.xml -->
<LinearLayout
    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:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        app:titleTextColor="@android:color/white"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
kotlin
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        // 设置导航图标
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu)

        // 自定义标题
        supportActionBar?.title = "主页"
        supportActionBar?.subtitle = "你好,用户!"
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.toolbar_menu, menu)
        return true
    }
}

将 Menu 集成到 Toolbar

Toolbar 通过回调 onCreateOptionsMenu 和 onOptionsItemSelected 与 Android Menu 系统集成。Menu 定义 action items——显示在 Toolbar 右侧的操作图标。如果 action items 放不下,会自动移到溢出菜单(三点)。开发人员通过属性 app:showAsAction 控制:always、ifRoom、never。

xml
<!-- res/menu/toolbar_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:title="搜索"
        app:showAsAction="ifRoom"
        app:actionViewClass="androidx.appcompat.widget.SearchView" />

    <item
        android:id="@+id/action_notifications"
        android:icon="@drawable/ic_notifications"
        android:title="通知"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_settings"
        android:title="设置"
        app:showAsAction="never" />
</menu>
kotlin
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.action_search -> {
            Toast.makeText(this, "搜索", Toast.LENGTH_SHORT).show()
            true
        }
        R.id.action_notifications -> {
            openNotifications()
            true
        }
        R.id.action_settings -> {
            openSettings()
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

Material 3:Center 和 Large Top App Bar

Material 3 引入了四种 Top App Bar 变体:Small(紧凑型,48 dp)、Center-aligned(标题居中)、Medium(112 dp 带增大标题)和 Large(168 dp 带大标题)。Medium 和 Large App Bar 支持可折叠行为——内容向上滚动时平滑收缩为 Small。动画由 CoordinatorLayout 和 AppBarLayout 管理。

Center-aligned Top App Bar——Material 3 的新变体,标题位于面板中央。这种样式常用于 Google 应用(Play Market、YouTube),推荐用于 action items 数量最少的屏幕。Small Top App Bar——经典 Toolbar,兼容旧版 Android。Medium 和 Large 适合标题是关键元素的屏幕(个人资料、主页)。

xml
<!-- Material 3 Large Top App Bar 与 CollapsingToolbarLayout -->
<CoordinatorLayout
    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">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="168dp"
            app:contentScrim="?attr/colorPrimary"
            app:titleEnabled="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin" />
        </CollapsingToolbarLayout>
    </AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:text="屏幕内容..." />
    </NestedScrollView>
</CoordinatorLayout>

Toolbar 高级定制

Toolbar 支持完全定制:更改高度、显示/隐藏动画、自定义子 View、徽标、导航图标、PopupMenu 以及与 CoordinatorLayout 集成。用于滚动时隐藏动画的 AppBarLayout 带有 scroll、enterAlways、snap 标志。Toolbar 下方图像的视差效果——采用 parallax 模式的 CollapsingToolbarLayout。

徽标和副标题通过 setLogo 和 setSubtitle 方法设置。导航图标通过 setNavigationIcon 和 setNavigationOnClickListener 配置。自定义 View 通过 addView 直接添加到 Toolbar。SearchView 使用带有 actionViewClass 的 MenuItem。对于深色主题,颜色从 Material 3 属性自动应用。

kotlin
// Toolbar 高级定制
with (toolbar) {
    // 徽标和标题
    setLogo(R.drawable.ic_logo)
    setTitle("我的应用")
    setSubtitle("版本 2.0")

    // 带处理器的导航图标
    setNavigationIcon(R.drawable.ic_drawer)
    setNavigationOnClickListener {
        drawerLayout.open()
    }

    // 自定义视图——主题开关
    val themeSwitch = Switch(this@MainActivity).apply {\n        thumbDrawable = ContextCompat.getDrawable(
            this@MainActivity, R.drawable.ic_theme
        )
    }
    addView(themeSwitch)

    // 自定义 PopupMenu
    setOnMenuItemClickListener { item ->
        Toast.makeText(this@MainActivity, item.title, Toast.LENGTH_SHORT).show()
        true
    }
}

常见问题

Toolbar 和 ActionBar 有什么区别?

ActionBar——Android 3.0–4.4 系统栏,定制有限。Toolbar——灵活的 Material Design 组件,可放置在布局的任何位置,可动画化并可填充自定义视图。Toolbar 通过 setSupportActionBar 完全取代 ActionBar。

如何在滚动时隐藏 Toolbar?

使用 CoordinatorLayout + AppBarLayout + CollapsingToolbarLayout。在 layout_scrollBehavior 中为 Toolbar 设置 scroll 标志。向下滚动时 Toolbar 隐藏,向上滚动时带动画出现。在 Material 3 中,Medium/Large Top App Bar 会收缩为 Small。

Toolbar 中可以放置多少个 action items?

限制是屏幕的物理宽度。建议 2–4 个 action items(图标)。其余的移到溢出菜单(三点)。通过 app:showAsAction 配置:always(始终显示)、ifRoom(如果有空间)、never(在溢出菜单中)。

如何将 SearchView 添加到 Toolbar?

SearchView 作为 action view 添加到 Menu 中。在 XML menu 中:app:actionViewClass="androidx.appcompat.widget.SearchView"。SearchView 自动折叠为搜索图标,点击时展开。支持语音搜索和通过 SearchRecentSuggestionsProvider 自动补全。

什么是 CollapsingToolbarLayout?

CollapsingToolbarLayout——Toolbar 的容器,在内容滚动时动画化折叠。与 CoordinatorLayout 和 AppBarLayout 一起使用。支持模式:pin(固定)、parallax(视差效果)。适用于标题中有图像的屏幕(个人资料、详情页)。

总结

  • Toolbar——灵活的 Android 工具栏,取代了 ActionBar 并与 Material Design 完全集成
  • Material 3 Top App Bar——四种变体:Small、Center-aligned、Medium、Large,滚动时行为不同
  • ActionBar——过时的系统栏,定制和动画有限
  • Menu 和 action items——通过带有 always/ifRoom/never 标志的 XML 菜单进行集成以管理可见性
  • CollapsingToolbarLayout——Toolbar 在滚动时的动画折叠,适用于标题中有图像的屏幕
  • 定制——徽标、副标题、自定义 View、SearchView、PopupMenu 和 Material 3 颜色
  • SearchView——内置 action view,支持语音输入和自动补全的搜索功能

我们将开发一款交钥匙移动应用程序

IT Sectr自2017年以来为初创企业和企业打造iOS和Android应用程序。我们将为您提供咨询并提出最佳解决方案。

讨论项目

另请阅读