如何将顶视图折叠成较小尺寸的视图?

How to have a collapsing of top view into a smaller sized view?

这个问题之前被问的太笼统和不清楚 here,所以我把它变得更加具体,并提供了我尝试过的内容的完整解释和代码。

背景

我需要模仿 Google 日历在顶部有一个视图的方式,该视图可以动画和下推底部的视图,但它有额外的、不同的行为。我总结了我在 3 个特征上尝试做的事情:

  1. 按下工具栏上的按钮将始终有效,以切换 expanding/collapsing 顶视图,同时有一个箭头图标可以改变其旋转。这就像 Google 日历应用程序。
  2. 顶视图将始终捕捉,就像在 Google 日历应用程序上一样。
  3. 当顶视图被折叠时,只有在工具栏上按下才能展开它。这就像 Google 日历应用
  4. 当顶视图展开时,在底视图滚动将只允许折叠。如果您尝试向另一个方向滚动,什么也不会发生,甚至不会滚动到底部视图。这就像 Google 日历应用
  5. 折叠后,顶视图将替换为较小的视图。这意味着它总是需要一些 space,高于底部视图。这与 Google 日历应用程序不同,因为在日历应用程序中,顶部视图一旦折叠就会完全消失。

Google 日历应用的外观如下:

滚动底部视图也会慢慢隐藏顶部视图:

问题

使用我过去发现的各种解决方案,我只成功实现了所需行为的一部分:

  1. 在工具栏中有一些 UI 是通过在其中包含一些视图(包括箭头视图)来完成的。对于手动 expanding/collapsing,我在 AppBarLayout 视图上使用 setExpanded。对于箭头的旋转,我使用 AppBarLayout 调整大小的侦听器,在其上使用 addOnOffsetChangedListener

  2. 通过将 snap 值添加到 CollapsingToolbarLayoutlayout_scrollFlags 属性中,可以轻松完成捕捉。然而,为了让它真正运行良好,没有奇怪的问题(报告here), I used .

  3. 阻止滚动时影响顶视图可以通过使用我在 #2 () 中使用的相同代码来完成,方法是在此处调用 setExpandEnabled。 这在顶视图折叠时效果很好。

  4. 与#3 类似,但遗憾的是,由于它使用了 setNestedScrollingEnabled,它是双向的,因此仅当顶视图折叠时效果很好。当它展开时,它仍然允许底部视图向上滚动,这与日历应用程序相反。展开时,我需要它只允许折叠,不允许真正滚动。

以下是优点和缺点的演示:

  1. 我完全没有做到这一点。我已经尝试了很多我想到的解决方案,将视图放在带有各种标志的各个地方。

简而言之,我成功地完成了 1-3,但没有完成 4-5。

密码

这是当前代码(也可作为整个项目 here):

ScrollingActivity.kt

class ScrollingActivity : AppCompatActivity(), AppBarTracking {

    private var mNestedView: MyRecyclerView? = null
    private var mAppBarOffset: Int = 0
    private var mAppBarIdle = false
    private var mAppBarMaxOffset: Int = 0

    private var isExpanded: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scrolling)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        mNestedView = findViewById(R.id.nestedView)
        app_bar.addOnOffsetChangedListener({ appBarLayout, verticalOffset ->
            mAppBarOffset = verticalOffset
            val totalScrollRange = appBarLayout.totalScrollRange
            val progress = (-verticalOffset).toFloat() / totalScrollRange
            arrowImageView.rotation = 180 + progress * 180
            isExpanded = verticalOffset == 0;
            mAppBarIdle = mAppBarOffset >= 0 || mAppBarOffset <= mAppBarMaxOffset
            if (mAppBarIdle)
                setExpandAndCollapseEnabled(isExpanded)
        })

        app_bar.post(Runnable { mAppBarMaxOffset = -app_bar.totalScrollRange })

        mNestedView!!.setAppBarTracking(this)
        mNestedView!!.layoutManager = LinearLayoutManager(this)
        mNestedView!!.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun getItemCount(): Int = 100

            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                return object : ViewHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false)) {}
            }

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                (holder.itemView.findViewById<View>(android.R.id.text1) as TextView).text = "item $position"
            }
        }

        expandCollapseButton.setOnClickListener({ v ->
            isExpanded = !isExpanded
            app_bar.setExpanded(isExpanded, true)
        })
    }

    private fun setExpandAndCollapseEnabled(enabled: Boolean) {
        mNestedView!!.isNestedScrollingEnabled = enabled
    }

    override fun isAppBarExpanded(): Boolean = mAppBarOffset == 0
    override fun isAppBarIdle(): Boolean = mAppBarIdle
}

MyRecyclerView.kt

/**A RecyclerView that allows temporary pausing of casuing its scroll to affect appBarLayout, based on  */
class MyRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle) {
    private var mAppBarTracking: AppBarTracking? = null
    private var mView: View? = null
    private var mTopPos: Int = 0
    private var mLayoutManager: LinearLayoutManager? = null

    interface AppBarTracking {
        fun isAppBarIdle(): Boolean
        fun isAppBarExpanded(): Boolean
    }

    override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?,
                                         type: Int): Boolean {
        if (type == ViewCompat.TYPE_NON_TOUCH && mAppBarTracking!!.isAppBarIdle()
                && isNestedScrollingEnabled) {
            if (dy > 0) {
                if (mAppBarTracking!!.isAppBarExpanded()) {
                    consumed!![1] = dy
                    return true
                }
            } else {
                mTopPos = mLayoutManager!!.findFirstVisibleItemPosition()
                if (mTopPos == 0) {
                    mView = mLayoutManager!!.findViewByPosition(mTopPos)
                    if (-mView!!.top + dy <= 0) {
                        consumed!![1] = dy - mView!!.top
                        return true
                    }
                }
            }
        }

        val returnValue = super.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type)
        if (offsetInWindow != null && !isNestedScrollingEnabled && offsetInWindow[1] != 0)
            offsetInWindow[1] = 0
        return returnValue
    }

    override fun setLayoutManager(layout: RecyclerView.LayoutManager) {
        super.setLayoutManager(layout)
        mLayoutManager = layoutManager as LinearLayoutManager
    }

    fun setAppBarTracking(appBarTracking: AppBarTracking) {
        mAppBarTracking = appBarTracking
    }

}

ScrollingCalendarBehavior.kt

class ScrollingCalendarBehavior(context: Context, attrs: AttributeSet) : AppBarLayout.Behavior(context, attrs) {
    override fun onInterceptTouchEvent(parent: CoordinatorLayout?, child: AppBarLayout?, ev: MotionEvent): Boolean = false
}

activity_scrolling.xml

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinatorLayout" xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:fitsSystemWindows="true" android:stateListAnimator="@null" android:theme="@style/AppTheme.AppBarOverlay"
        app:expanded="false" app:layout_behavior="com.example.user.expandingtopviewtest.ScrollingCalendarBehavior"
        tools:targetApi="lollipop">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout" android:layout_width="match_parent"
            android:layout_height="match_parent" android:fitsSystemWindows="true"
            android:minHeight="?attr/actionBarSize" app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap" app:statusBarScrim="?attr/colorPrimaryDark">

            <LinearLayout
                android:layout_width="match_parent" android:layout_height="250dp"
                android:layout_marginTop="?attr/actionBarSize" app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="1.0">

                <TextView
                    android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="10dp"
                    android:paddingRight="10dp" android:text="some large, expanded view"/>
            </LinearLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar" android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <android.support.constraint.ConstraintLayout
                    android:id="@+id/expandCollapseButton" android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize" android:background="?android:selectableItemBackground"
                    android:clickable="true" android:focusable="true" android:orientation="vertical">

                    <TextView
                        android:id="@+id/titleTextView" android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:layout_marginBottom="8dp"
                        android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:ellipsize="end"
                        android:gravity="center" android:maxLines="1" android:text="title"
                        android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
                        android:textColor="@android:color/white" app:layout_constraintBottom_toBottomOf="parent"
                        app:layout_constraintStart_toStartOf="parent"/>

                    <ImageView
                        android:id="@+id/arrowImageView" android:layout_width="wrap_content" android:layout_height="0dp"
                        android:layout_marginLeft="8dp" android:layout_marginStart="8dp"
                        app:layout_constraintBottom_toBottomOf="@+id/titleTextView"
                        app:layout_constraintStart_toEndOf="@+id/titleTextView"
                        app:layout_constraintTop_toTopOf="@+id/titleTextView"
                        app:srcCompat="@android:drawable/arrow_down_float"
                        tools:ignore="ContentDescription,RtlHardcoded"/>

                </android.support.constraint.ConstraintLayout>
            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <com.example.user.expandingtopviewtest.MyRecyclerView
        android:id="@+id/nestedView" android:layout_width="match_parent" android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".ScrollingActivity"/>

</android.support.design.widget.CoordinatorLayout>

问题

  1. 如何在展开顶部视图时阻止滚动,但在滚动时允许折叠?

  2. 如何使顶视图在折叠时被替换为较小的视图(并在展开时变回大视图),而不是完全消失?


更新

尽管我已经了解了我所询问的基本内容,但当前代码仍然存在 2 个问题(在 Github、here 上可用):

  1. 小视图(您在折叠状态下看到的视图)具有内部视图,需要对其产生点击效果。在它们上面使用 android:background="?attr/selectableItemBackgroundBorderless" 并在展开时单击此区域时,单击是在小视图上完成的。我通过将小视图放在不同的工具栏上来处理它,但是点击效果根本没有显示出来。我已经写过关于这个 here 的文章,包括示例项目。

修复方法如下:

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinatorLayout" xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content"
        android:fitsSystemWindows="true" android:stateListAnimator="@null" android:theme="@style/AppTheme.AppBarOverlay"
        app:expanded="false" app:layout_behavior="com.example.expandedtopviewtestupdate.ScrollingCalendarBehavior"
        tools:targetApi="lollipop">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout" android:layout_width="match_parent"
            android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"
            android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap|enterAlways"
            app:statusBarScrim="?attr/colorPrimaryDark">

            <!--large view -->
            <LinearLayout
                android:id="@+id/largeView" android:layout_width="match_parent" android:layout_height="280dp"
                android:layout_marginTop="?attr/actionBarSize" android:orientation="vertical"
                app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="1.0">

                <TextView
                    android:id="@+id/largeTextView" android:layout_width="match_parent"
                    android:layout_height="match_parent" android:layout_gravity="center"
                    android:background="?attr/selectableItemBackgroundBorderless" android:clickable="true"
                    android:focusable="true" android:focusableInTouchMode="false" android:gravity="center"
                    android:text="largeView" android:textSize="14dp" tools:background="?attr/colorPrimary"
                    tools:layout_gravity="top|center_horizontal" tools:layout_height="40dp" tools:layout_width="40dp"
                    tools:text="1"/>

            </LinearLayout>

            <!--top toolbar-->
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/small_view_height" app:contentInsetStart="0dp"
                app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay">

                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true"
                    android:focusable="true">

                    <LinearLayout
                        android:id="@+id/expandCollapseButton" android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        android:background="?android:selectableItemBackground" android:gravity="center_vertical"
                        android:orientation="horizontal" app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent">

                        <TextView
                            android:id="@+id/titleTextView" android:layout_width="wrap_content"
                            android:layout_height="wrap_content" android:ellipsize="end" android:gravity="center"
                            android:maxLines="1" android:text="title"
                            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
                            android:textColor="@android:color/white"/>

                        <ImageView
                            android:id="@+id/arrowImageView" android:layout_width="wrap_content"
                            android:layout_height="wrap_content" android:layout_marginLeft="8dp"
                            android:layout_marginStart="8dp" app:srcCompat="@android:drawable/arrow_up_float"
                            tools:ignore="ContentDescription,RtlHardcoded"/>
                    </LinearLayout>

                </android.support.constraint.ConstraintLayout>

            </android.support.v7.widget.Toolbar>

            <android.support.v7.widget.Toolbar
                android:id="@+id/smallLayoutContainer" android:layout_width="match_parent"
                android:layout_height="wrap_content" android:layout_marginTop="?attr/actionBarSize"
                android:clipChildren="false" android:clipToPadding="false" app:contentInsetStart="0dp"
                app:layout_collapseMode="pin">
                <!--small view-->
                <LinearLayout
                    android:id="@+id/smallLayout" android:layout_width="match_parent"
                    android:layout_height="@dimen/small_view_height" android:clipChildren="false"
                    android:clipToPadding="false" android:orientation="horizontal" tools:background="#ff330000"
                    tools:layout_height="@dimen/small_view_height">

                    <TextView
                        android:id="@+id/smallTextView" android:layout_width="match_parent"
                        android:layout_height="match_parent" android:layout_gravity="center"
                        android:background="?attr/selectableItemBackgroundBorderless" android:clickable="true"
                        android:focusable="true" android:focusableInTouchMode="false" android:gravity="center"
                        android:text="smallView" android:textSize="14dp" tools:background="?attr/colorPrimary"
                        tools:layout_gravity="top|center_horizontal" tools:layout_height="40dp"
                        tools:layout_width="40dp" tools:text="1"/>

                </LinearLayout>
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <com.example.expandedtopviewtestupdate.MyRecyclerView
        android:id="@+id/nestedView" android:layout_width="match_parent" android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".ScrollingActivity"/>

</android.support.design.widget.CoordinatorLayout>
  1. Google 日历允许在工具栏本身上执行向下滚动手势,以触发显示月视图。我只成功地在那里添加了一个点击事件,但没有滚动。它是这样的:

注意:完整的更新项目可用 here

How can I make the scrolling being blocked when the top view is expanded, yet allow to collapse while scrolling ?

问题 #1: 当应用栏未折叠时,RecyclerView 根本无法滚动。要解决此问题,请将 enterAlways 添加到 CollapsingToolbarLayout 的滚动标志,如下所示:

<android.support.design.widget.CollapsingToolbarLayout
    android:id="@+id/collapsingToolbarLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:fitsSystemWindows="true"
    app:layout_scrollFlags="scroll|exitUntilCollapsed|snap|enterAlways"
    app:statusBarScrim="?attr/colorPrimaryDark">

enterAlways 不会导致应用栏在关闭时打开,因为您正在抑制该功能,但可以正常工作。

问题 #2: 当应用栏完全展开时,不应允许 RecyclerView 向上滚动。这恰好是问题 #1 的不同问题。

[已更新] 要更正此问题,请修改 RecyclerView 的行为以在 RecyclerView 尝试向上滚动和应用栏时消耗滚动已完全展开或将在 scroll(dy) 被消耗后完全展开。 RecyclerView 可以向上滚动,但它永远不会看到该操作,因为它的行为 SlidingPanelBehavior 会消耗滚动。如果应用栏未完全展开但会在当前滚动条被消耗后展开,该行为会通过调用修改 dy 并在完全消耗滚动条之前调用 super 来强制应用栏完全展开。 (参见 SlidingPanelBehavior#onNestedPreScroll())。 (在之前的回答中,修改了 appBar 行为。将行为更改放在 RecyclerView 上是更好的选择。)

问题 #3: 当嵌套滚动已处于所需状态时,将 RecyclerView 的嵌套滚动设置为 enable/disabled 会导致问题。为避免这些问题,只有在 ScrollingActivity:

中真正进行更改时才更改嵌套滚动的状态
private void setExpandAndCollapseEnabled(boolean enabled) {
    if (mNestedView.isNestedScrollingEnabled() != enabled) {
        mNestedView.setNestedScrollingEnabled(enabled);
    }
}

这是测试应用程序在进行上述更改后的行为方式:

有上述变化的模块在post.

的末尾

How can I make the top view be replaced with a smaller one when collapsed (and back to large one when expanded), instead of completely disappear ?

[更新] 使较小的视图成为 CollapsingToolbarLayout 的直接子视图,因此它是 Toolbar 的兄弟视图。下面是这种方法的演示。较小视图的 collapseMode 设置为 pin。较小视图的边距以及工具栏的边距都进行了调整,因此较小的视图紧靠工具栏下方。由于 CollapsingToolbarLayout 是一个 FrameLayout,视图堆栈和 FrameLayout 的高度刚好成为最高子视图的高度。 这种结构可以避免insets需要调整的问题和点击效果缺失的问题。

最后一个问题仍然存在,向下拖动应用栏应该打开它,假设向下拖动较小的视图不应该打开应用栏。使用 AppBarLayout.BehaviorsetDragCallback 允许应用栏在拖动时打开。由于较小的视图已合并到 appBar 中,因此将其向下拖动将打开 appbar。为防止这种情况,应用栏附加了一个名为 MyAppBarBehavior 的新行为。此行为与 MainActivity 中的代码结合可防止拖动较小的视图以打开应用栏,但允许拖动工具栏。

activity_main.xml

<android.support.design.widget.CoordinatorLayout 
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:stateListAnimator="@null"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:expanded="false"
        app:layout_behavior=".MyAppBarBehavior"
        tools:targetApi="lollipop">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="false"
            android:clipToPadding="false"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap|enterAlways"
            app:statusBarScrim="?attr/colorPrimaryDark">

            <!--large view -->
            <LinearLayout
                android:id="@+id/largeView"
                android:layout_width="match_parent"
                android:layout_height="280dp"
                android:layout_marginTop="?attr/actionBarSize"
                android:orientation="vertical"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="1.0">

                <TextView
                    android:id="@+id/largeTextView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:clickable="true"
                    android:focusable="true"
                    android:focusableInTouchMode="false"
                    android:gravity="center"
                    android:text="largeView"
                    android:textSize="14dp"
                    tools:background="?attr/colorPrimary"
                    tools:layout_gravity="top|center_horizontal"
                    tools:layout_height="40dp"
                    tools:layout_width="40dp"
                    tools:text="1" />

            </LinearLayout>

            <!--top toolbar-->
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/small_view_height"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:focusable="true">

                    <LinearLayout
                        android:id="@+id/expandCollapseButton"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        android:background="?android:selectableItemBackground"
                        android:gravity="center_vertical"
                        android:orientation="horizontal"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent">

                        <TextView
                            android:id="@+id/titleTextView"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:ellipsize="end"
                            android:gravity="center"
                            android:maxLines="1"
                            android:text="title"
                            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
                            android:textColor="@android:color/white" />

                        <ImageView
                            android:id="@+id/arrowImageView"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:layout_marginStart="8dp"
                            app:srcCompat="@android:drawable/arrow_up_float"
                            tools:ignore="ContentDescription,RtlHardcoded" />
                    </LinearLayout>

                </android.support.constraint.ConstraintLayout>

            </android.support.v7.widget.Toolbar>

            <!--small view-->
            <LinearLayout
                android:id="@+id/smallLayout"
                android:layout_width="match_parent"
                android:layout_height="@dimen/small_view_height"
                android:layout_marginTop="?attr/actionBarSize"
                android:clipChildren="false"
                android:clipToPadding="false"
                android:orientation="horizontal"
                app:layout_collapseMode="pin"
                tools:background="#ff330000"
                tools:layout_height="@dimen/small_view_height">

                <TextView
                    android:id="@+id/smallTextView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:clickable="true"
                    android:focusable="true"
                    android:focusableInTouchMode="false"
                    android:gravity="center"
                    android:text="smallView"
                    android:textSize="14dp"
                    tools:background="?attr/colorPrimary"
                    tools:layout_gravity="top|center_horizontal"
                    tools:layout_height="40dp"
                    tools:layout_width="40dp"
                    tools:text="1" />

            </LinearLayout>
        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <com.example.expandedtopviewtestupdate.MyRecyclerView
        android:id="@+id/nestedView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".SlidingPanelBehavior" />

</android.support.design.widget.CoordinatorLayout>

最后,在 addOnOffsetChangedListener 中添加以下代码以在应用栏扩展和收缩时在较小的视图中淡出 out/fade。一旦视图的 alpha 为零(不可见),将其可见性设置为 View.INVISIBLE,这样就无法单击它。一旦视图的 alpha 增加到零以上,通过将其可见性设置为 View.VISIBLE.

使其可见和可点击
mSmallLayout.setAlpha((float) -verticalOffset / totalScrollRange);
// If the small layout is not visible, make it officially invisible so
// it can't receive clicks.
if (alpha == 0) {
    mSmallLayout.setVisibility(View.INVISIBLE);
} else if (mSmallLayout.getVisibility() == View.INVISIBLE) {
    mSmallLayout.setVisibility(View.VISIBLE);
}

结果如下:

这是合并了上述所有更改的新模块。

MainActivity.java

public class MainActivity extends AppCompatActivity
    implements MyRecyclerView.AppBarTracking {
    private MyRecyclerView mNestedView;
    private int mAppBarOffset = 0;
    private boolean mAppBarIdle = true;
    private int mAppBarMaxOffset = 0;
    private AppBarLayout mAppBar;
    private boolean mIsExpanded = false;
    private ImageView mArrowImageView;
    private LinearLayout mSmallLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LinearLayout expandCollapse;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        expandCollapse = findViewById(R.id.expandCollapseButton);
        mArrowImageView = findViewById(R.id.arrowImageView);
        mNestedView = findViewById(R.id.nestedView);
        mAppBar = findViewById(R.id.app_bar);
        mSmallLayout = findViewById(R.id.smallLayout);

        // Log when the small text view is clicked
        findViewById(R.id.smallTextView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "<<<<click small layout");
            }
        });

        // Log when the big text view is clicked.
        findViewById(R.id.largeTextView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "<<<<click big view");
            }
        });

        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        if (ab != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        mAppBar.post(new Runnable() {
            @Override
            public void run() {
                mAppBarMaxOffset = -mAppBar.getTotalScrollRange();

                CoordinatorLayout.LayoutParams lp =
                    (CoordinatorLayout.LayoutParams) mAppBar.getLayoutParams();
                MyAppBarBehavior behavior = (MyAppBarBehavior) lp.getBehavior();
                // Only allow drag-to-open if the drag touch is on the toolbar.
                // Once open, all drags are allowed.
                if (behavior != null) {
                    behavior.setCanOpenBottom(findViewById(R.id.toolbar).getHeight());
                }
            }
        });

        mNestedView.setAppBarTracking(this);
        mNestedView.setLayoutManager(new LinearLayoutManager(this));
        mNestedView.setAdapter(new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return new ViewHolder(
                    LayoutInflater.from(parent.getContext())
                        .inflate(android.R.layout.simple_list_item_1, parent, false));
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                ((TextView) holder.itemView.findViewById(android.R.id.text1))
                    .setText("Item " + position);
            }

            @Override
            public int getItemCount() {
                return 200;
            }

            class ViewHolder extends RecyclerView.ViewHolder {
                public ViewHolder(View view) {
                    super(view);
                }
            }
        });

        mAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                mAppBarOffset = verticalOffset;
                int totalScrollRange = appBarLayout.getTotalScrollRange();
                float progress = (float) (-verticalOffset) / (float) totalScrollRange;
                mArrowImageView.setRotation(-progress * 180);
                mIsExpanded = verticalOffset == 0;
                mAppBarIdle = mAppBarOffset >= 0 || mAppBarOffset <= mAppBarMaxOffset;
                float alpha = (float) -verticalOffset / totalScrollRange;
                mSmallLayout.setAlpha(alpha);

                // If the small layout is not visible, make it officially invisible so
                // it can't receive clicks.
                if (alpha == 0) {
                    mSmallLayout.setVisibility(View.INVISIBLE);
                } else if (mSmallLayout.getVisibility() == View.INVISIBLE) {
                    mSmallLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        expandCollapse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setExpandAndCollapseEnabled(true);
                if (mIsExpanded) {
                    setExpandAndCollapseEnabled(false);
                }
                mIsExpanded = !mIsExpanded;
                mNestedView.stopScroll();
                mAppBar.setExpanded(mIsExpanded, true);
            }
        });
    }

    private void setExpandAndCollapseEnabled(boolean enabled) {
        if (mNestedView.isNestedScrollingEnabled() != enabled) {
            mNestedView.setNestedScrollingEnabled(enabled);
        }
    }

    @Override
    public boolean isAppBarExpanded() {
        return mAppBarOffset == 0;
    }

    @Override
    public boolean isAppBarIdle() {
        return mAppBarIdle;
    }

    private static final String TAG = "MainActivity";
}

SlidingPanelBehavior.java

public class SlidingPanelBehavior extends AppBarLayout.ScrollingViewBehavior {
    private AppBarLayout mAppBar;

    public SlidingPanelBehavior() {
        super();
    }

    public SlidingPanelBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(final CoordinatorLayout parent, View child, View dependency) {
        if (mAppBar == null && dependency instanceof AppBarLayout) {
            // Capture our appbar for later use.
            mAppBar = (AppBarLayout) dependency;
        }
        return dependency instanceof AppBarLayout;
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, View child, MotionEvent event) {
        int action = event.getAction();

        if (event.getAction() != MotionEvent.ACTION_DOWN) { // Only want "down" events
            return false;
        }
        if (getAppBarLayoutOffset(mAppBar) == -mAppBar.getTotalScrollRange()) {
            // When appbar is collapsed, don't let it open through nested scrolling.
            setNestedScrollingEnabledWithTest((NestedScrollingChild2) child, false);
        } else {
            // Appbar is partially to fully expanded. Set nested scrolling enabled to activate
            // the methods within this behavior.
            setNestedScrollingEnabledWithTest((NestedScrollingChild2) child, true);
        }
        return false;
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,
                                       @NonNull View directTargetChild, @NonNull View target,
                                       int axes, int type) {
        //noinspection RedundantCast
        return ((NestedScrollingChild2) child).isNestedScrollingEnabled();
    }

    @Override
    public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child,
                                  @NonNull View target, int dx, int dy, @NonNull int[] consumed,
                                  int type) {
        // How many pixels we must scroll to fully expand the appbar. This value is <= 0.
        final int appBarOffset = getAppBarLayoutOffset(mAppBar);

        // Check to see if this scroll will expand the appbar 100% or collapse it fully.
        if (dy <= appBarOffset) {
            // Scroll by the amount that will fully expand the appbar and dispose of the rest (dy).
            super.onNestedPreScroll(coordinatorLayout, mAppBar, target, dx,
                                    appBarOffset, consumed, type);
            consumed[1] += dy;
        } else if (dy >= (mAppBar.getTotalScrollRange() + appBarOffset)) {
            // This scroll will collapse the appbar. Collapse it and dispose of the rest.
            super.onNestedPreScroll(coordinatorLayout, mAppBar, target, dx,
                                    mAppBar.getTotalScrollRange() + appBarOffset,
                                    consumed, type);
            consumed[1] += dy;
        } else {
            // This scroll will leave the appbar partially open. Just do normal stuff.
            super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        }
    }

    /**
     * {@code onNestedPreFling()} is overriden to address a nested scrolling defect that was
     * introduced in API 26. This method prevent the appbar from misbehaving when scrolled/flung.
     * <p>
     * Refer to <a href="https://issuetracker.google.com/issues/65448468"  target="_blank">"Bug in design support library"</a>
     */

    @Override
    public boolean onNestedPreFling(@NonNull CoordinatorLayout coordinatorLayout,
                                    @NonNull View child, @NonNull View target,
                                    float velocityX, float velocityY) {
        //noinspection RedundantCast
        if (((NestedScrollingChild2) child).isNestedScrollingEnabled()) {
            // Just stop the nested fling and let the appbar settle into place.
            ((NestedScrollingChild2) child).stopNestedScroll(ViewCompat.TYPE_NON_TOUCH);
            return true;
        }
        return super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY);
    }

    private static int getAppBarLayoutOffset(AppBarLayout appBar) {
        final CoordinatorLayout.Behavior behavior =
            ((CoordinatorLayout.LayoutParams) appBar.getLayoutParams()).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            return ((AppBarLayout.Behavior) behavior).getTopAndBottomOffset();
        }
        return 0;
    }

    // Something goes amiss when the flag it set to its current value, so only call
    // setNestedScrollingEnabled() if it will result in a change.
    private void setNestedScrollingEnabledWithTest(NestedScrollingChild2 child, boolean enabled) {
        if (child.isNestedScrollingEnabled() != enabled) {
            child.setNestedScrollingEnabled(enabled);
        }
    }

    @SuppressWarnings("unused")
    private static final String TAG = "SlidingPanelBehavior";
}

MyRecyclerView.kt

/**A RecyclerView that allows temporary pausing of casuing its scroll to affect appBarLayout, based on  */
class MyRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : RecyclerView(context, attrs, defStyle) {
    private var mAppBarTracking: AppBarTracking? = null
    private var mView: View? = null
    private var mTopPos: Int = 0
    private var mLayoutManager: LinearLayoutManager? = null

    interface AppBarTracking {
        fun isAppBarIdle(): Boolean
        fun isAppBarExpanded(): Boolean
    }

    override fun dispatchNestedPreScroll(dx: Int, dy: Int, consumed: IntArray?, offsetInWindow: IntArray?, type: Int): Boolean {
        if (type == ViewCompat.TYPE_NON_TOUCH && mAppBarTracking!!.isAppBarIdle()
                && isNestedScrollingEnabled) {
            if (dy > 0) {
                if (mAppBarTracking!!.isAppBarExpanded()) {
                    consumed!![1] = dy
                    return true
                }
            } else {
                mTopPos = mLayoutManager!!.findFirstVisibleItemPosition()
                if (mTopPos == 0) {
                    mView = mLayoutManager!!.findViewByPosition(mTopPos)
                    if (-mView!!.top + dy <= 0) {
                        consumed!![1] = dy - mView!!.top
                        return true
                    }
                }
            }
        }
        if (dy < 0 && type == ViewCompat.TYPE_TOUCH && mAppBarTracking!!.isAppBarExpanded()) {
            consumed!![1] = dy
            return true
        }

        val returnValue = super.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type)
        if (offsetInWindow != null && !isNestedScrollingEnabled && offsetInWindow[1] != 0)
            offsetInWindow[1] = 0
        return returnValue
    }

    override fun setLayoutManager(layout: RecyclerView.LayoutManager) {
        super.setLayoutManager(layout)
        mLayoutManager = layoutManager as LinearLayoutManager
    }

    fun setAppBarTracking(appBarTracking: AppBarTracking) {
        mAppBarTracking = appBarTracking
    }

    override fun fling(velocityX: Int, velocityY: Int): Boolean {
        var velocityY = velocityY
        if (!mAppBarTracking!!.isAppBarIdle()) {
            val vc = ViewConfiguration.get(context)
            velocityY = if (velocityY < 0) -vc.scaledMinimumFlingVelocity
            else vc.scaledMinimumFlingVelocity
        }

        return super.fling(velocityX, velocityY)
    }
}

MyAppBarBehavior.java

/**
 * Attach this behavior to AppBarLayout to disable the bottom portion of a closed appBar
 * so it cannot be touched to open the appBar. This behavior is helpful if there is some
 * portion of the appBar that displays when the appBar is closed, but should not open the appBar
 * when the appBar is closed.
 */
public class MyAppBarBehavior extends AppBarLayout.Behavior {

    // Touch above this y-axis value can open the appBar.
    private int mCanOpenBottom;

    // Determines if the appBar can be dragged open or not via direct touch on the appBar.
    private boolean mCanDrag = true;

    @SuppressWarnings("unused")
    public MyAppBarBehavior() {
        init();
    }

    @SuppressWarnings("unused")
    public MyAppBarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setDragCallback(new AppBarLayout.Behavior.DragCallback() {
            @Override
            public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                return mCanDrag;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent,
                                         AppBarLayout child,
                                         MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // If appBar is closed. Only allow scrolling in defined area.
            if (child.getTop() <= -child.getTotalScrollRange()) {
                mCanDrag = event.getY() < mCanOpenBottom;
            }
        }
        return super.onInterceptTouchEvent(parent, child, event);
    }

    public void setCanOpenBottom(int bottom) {
        mCanOpenBottom = bottom;
    }
}