创建具有最小高度的自定义 AppBarLayout 子项?

Create custom AppBarLayout child with minimum height?

我想创建一个自定义视图,它将成为 AppBarLayout 的子视图。当我向上滚动时,我需要这个视图部分折叠,但不是完全折叠。它将有一个最小高度,并在小尺寸模式下固定在 AppBarLayout 的顶部,然后在向下滚动视图时扩展回大尺寸模式。

我花了很多时间查看 AppBarLayout 和 CoordinatorLayout 的源代码,但到目前为止我没有找到一种方法来做我想做的事情。当向上滚动视图时,AppBarLayout 的子项看起来必须保持可见或完全消失。

任何人都可以建议一种方法来创建 AppBarLayout 的子项,该子项将以这种方式运行吗?

谢谢

食谱如下:

如果您设置 android:minHeightAppBarLayout 将尊重该值,不会滚动超出会使您的组件变小的点。所以你的 XML 布局可能是这样的:

    <com.example.CustomCollapsingLayout
        android:layout_width="match_parent"
        android:layout_height="320dp"
        android:minHeight="108dp"
        android:fitsSystemWindows="true"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

接下来,您想让 class 向父 AppBarLayout 注册一个 OnOffsetChangedListener。当应用栏滚动时,您的组件将获得事件,以便您了解如何配置视图。

class OnOffsetChangedListener implements AppBarLayout.OnOffsetChangedListener {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

            final int scrollRange = appBarLayout.getTotalScrollRange();
            float offsetFactor = (float) (-verticalOffset) / (float) scrollRange;
            ...

这将向您展示如何找到总滚动范围,然后找到总滚动范围与当前滚动位置之间的比率,即应用栏在其滚动中的位置。

你应该做 CollapsingToolbarLayout 做的事;覆盖 onAttachedToWindow 并在那里添加侦听器:

        // Add an OnOffsetChangedListener if possible
        final ViewParent parent = getParent();
        if (parent instanceof AppBarLayout) {
            if (mOnOffsetChangedListener == null) {
                mOnOffsetChangedListener = new OnOffsetChangedListener();
            }
            ((AppBarLayout) parent).addOnOffsetChangedListener(mOnOffsetChangedListener);
        }

看看 source code for CollapsingToolbarLayout,它会给您一些想法。您的视图需要做很多相同的事情。

您还可以查看我的示例项目,其中的图像会随着工具栏的滚动而缩放和移动:https://github.com/klarson2/Collapsing-Image