返回

进阶之路:用 CollapsingToolbarLayout 高仿稀土掘金个人中心页

Android

前言

CollapsingToolbarLayout 是 Android Material Design 提供的一个组件,通过搭配 AppBarLayout 可实现 toolbar 的折叠效果。本篇文章将通过仿实现稀土掘金个人中心页,详细介绍如何使用 CollapsingToolbarLayout 和 AppBarLayout。

基础介绍

CollapsingToolbarLayout

CollapsingToolbarLayout 是一个布局容器,它可以容纳一个或多个子控件。当 CollapsingToolbarLayout 的高度发生变化时,它的子控件也会随之变化。我们可以利用这一点来实现 toolbar 的折叠效果。

AppBarLayout

AppBarLayout 是一个垂直布局容器,它可以容纳一个或多个子控件。AppBarLayout 的主要作用是为其子控件提供滚动支持。当 AppBarLayout 的高度发生变化时,它的子控件也会随之变化。

实现折叠效果

步骤 1:在布局文件中添加 CollapsingToolbarLayout 和 AppBarLayout

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

        <com.google.android.material.collapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!-- Toolbar -->

        </com.google.android.material.collapsingToolbarLayout>

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

    <!-- 其他控件 -->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

步骤 2:在代码中设置 CollapsingToolbarLayout 和 AppBarLayout 的属性

// 设置 CollapsingToolbarLayout 的标题
collapsingToolbarLayout.setTitle("个人中心");

// 设置 AppBarLayout 的展开高度
appBarLayout.setExpanded(true);

// 设置 AppBarLayout 的折叠高度
appBarLayout.setCollapsedHeight(Toolbar.LayoutParams.MATCH_PARENT);

// 设置 AppBarLayout 的滚动监听器
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        // 当 AppBarLayout 的高度发生变化时,更新 toolbar 的标题
        collapsingToolbarLayout.setTitle("个人中心" + verticalOffset);
    }
});

注意事项

1. Toolbar 的高度

Toolbar 的高度必须与 CollapsingToolbarLayout 的高度相同,否则折叠效果无法正常显示。

2. AppBarLayout 的滚动监听器

在设置 AppBarLayout 的滚动监听器时,需要特别注意 verticalOffset 的值。verticalOffset 是 AppBarLayout 的当前高度与展开高度的差值。当 AppBarLayout 完全展开时,verticalOffset 为 0;当 AppBarLayout 完全折叠时,verticalOffset 为负值。

3. CollapsingToolbarLayout 的标题

CollapsingToolbarLayout 的标题可以是任何内容,但建议使用简短的标题,以避免遮挡其他内容。

结语

通过本篇文章,我们详细介绍了如何使用 CollapsingToolbarLayout 和 AppBarLayout 实现 toolbar 的折叠效果。这些组件的使用方法相对简单,但可以为应用程序增添动态感和美感。希望读者能够通过本教程掌握 CollapsingToolbarLayout 和 AppBarLayout 的用法,并将其应用到自己的应用程序中。