Skip to content

顶部应用栏 (Top App Bars)

源:Top app bars

顶部应用栏(在 M3 中简称为 App Bar)放置在屏幕顶部,帮助用户在应用中进行导航和操作。

App Bar 变体

变体对比

M3 提供了四种主要的顶部栏变体:

类型描述适用场景
Search app bar带有搜索输入框的栏以搜索为核心功能的首页
Small最小高度,单行标题详情页、设置页
Medium flexible初始标题较大,滚动时折叠分类首页
Large flexible初始标题巨大,提供最强视觉引导应用主入口

核心属性

容器属性

元素属性默认值
颜色android:background?attr/colorSurface
海拔 (Elevation)android:elevation4dp

标题与导航

元素属性相关方法
标题文本app:titlesetTitle()
副标题app:subtitlesetSubtitle()
导航图标app:navigationIconsetNavigationIcon()
标题居中app:titleCenteredtrue / false

代码实现

1. 基础用法 (Small)

xml
<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/topAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        app:title="页面标题"
        app:menu="@menu/top_app_bar"
        app:navigationIcon="@drawable/ic_close" />

</com.google.android.material.appbar.AppBarLayout>
kotlin
topAppBar.setNavigationOnClickListener {
    // 处理导航图标点击
}

topAppBar.setOnMenuItemClickListener { menuItem ->
    when (menuItem.itemId) {
        R.id.favorite -> {
            // 处理收藏
            true
        }
        else -> false
    }
}

2. 可折叠应用栏 (Large)

使用 CollapsingToolbarLayout 实现滚动时的标题缩放效果。

xml
<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        style="?attr/collapsingToolbarLayoutLargeStyle"
        android:layout_width="match_parent"
        android:layout_height="?attr/collapsingToolbarLayoutLargeSize"
        app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

        <com.google.android.material.appbar.MaterialToolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

滚动行为

自动提升

使用 app:liftOnScroll="true",当下方内容滚动时,App Bar 会自动增加阴影并改变颜色以示区分。

xml
<com.google.android.material.appbar.AppBarLayout
    app:liftOnScroll="true">
    ...
</com.google.android.material.appbar.AppBarLayout>

压缩效果 (Compress)

你可以设置 app:layout_scrollEffect="compress",使 App Bar 在滚动时产生裁剪压缩效果,这是 M3 推荐的新视觉表现。


上下文操作栏 (Contextual action bar)

当用户选择项目时,App Bar 可以转换为上下文操作栏。

上下文操作栏示例

kotlin
val callback = object : ActionMode.Callback {
    override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
        mode?.menuInflater?.inflate(R.menu.contextual_menu, menu)
        return true
    }
    // ... 其他回调
}
startSupportActionMode(callback)