折叠伸缩工具栏 CollapsingToolbarLayout

时间:2025-05-01 08:03:49
PS:这是一个超级超级垃圾的控件,强烈建议放弃使用!

一个类似的效果的库,有800个星星:https://github.com/yanzhenjie/Sofia
Android沉浸式效果的实现,状态栏和导航栏均支持设置颜色、渐变色、图片、透明度、内容入侵和状态栏深色字体;兼容竖屏、横屏,当屏幕旋转时会自动适配。
1
Android沉浸式效果的实现,状态栏和导航栏均支持设置颜色、渐变色、图片、透明度、内容入侵和状态栏深色字体;兼容竖屏、横屏,当屏幕旋转时会自动适配。

简介

在AndroidStudio中新建一个Activity时选择ScrollingActivity模板,它实现的就是简单的折叠式工具栏效果:Toolbar是透明的,有一个背景图片以及大标题,随着页面向上滑动,其标题逐渐缩放到Toolbar上,而背景图片则在滑动到一定程度后变成了Toolbar的颜色。其实这种效果在GitHub上面已经有很多开源库实现了,但是Google在其推出的Design Library库中也给出了一个这种控件,让我们很方便地实现了这种效果。这个控件就是CollapsingToolbarLayout,它是一个增强型的FrameLayout。

常用xml属性介绍

一般属性

  • contentScrim:当Toolbar折叠到一定程度时的背景颜色
  • title:当titleEnable设置为true的时候(默认),显示的可缩放的标题
  • scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间
  • app:collapsedTitleGravity="left"  Specifies how the title should be positioned when collapsed.  指定在折叠之后标题放置的位置
  • app:collapsedTitleTextAppearance="@color/colorPrimary"  The text appearance of the CollapsingToolbarLayouts title when it is fully 'collapsed'。Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name". 在折叠的时候标题文字的外观。必须引用另一个资源
  • app:contentScrim="#ff5252" The drawable to use as a scrim on top of the CollapsingToolbarLayouts content when it has been scrolled sufficiently off screen. 指定在折叠之后的背景色
  • app:expandedTitleGravity="left|bottom" Specifies how the title should be positioned when expanded. 在展开的时候 标题放置的位置
  • app:expandedTitleMargin="16dp" Specifies extra space on the start, top, end and bottom sides of the the expanded title text. 设置边界距离,还可以单独设置Bottom、Top、Left、Right等
  • app:expandedTitleTextAppearance 在展开的时候标题文字的外观
  • app:scrimAnimationDuration="200"  Specifies the duration used for scrim visibility animations. 控制Toolbar收缩时,颜色变化持续时间
  • app:scrimVisibleHeightTrigger="150dp"  Specifies the amount of visible height in pixels used to define when to trigger a scrim visibility change.当可视高度变为多少时(折叠或展开时)触发背景颜色改变
  • app:statusBarScrim="#123456" The drawable to use as a scrim for the status bar content when the CollapsingToolbarLayout has been scrolled sufficiently off screen. 在折叠的时候 状态栏 的背景颜色(一般不需要设置)
  • app:title="Title" The title to show when titleEnabled is set to true. 如果标题可用的话 显示的标题文字
  • app:titleEnabled="true" Whether the CollapsingToolbarLayout should draw its own shrinking/growing title. 是否显示标题
  • app:toolbarId="@id/toolbar" The id of the primary Toolbar child that you wish to use for the purpose of collapsing.在折叠的时候 显示的toolbar的id

layout_scrollFlags属性

一般开发中,CollapsingToolbarLayout不会单独出现在布局文件中,而是作为另一个控件CoordinatorLayout的子元素出现,CoordinatorLayout这个控件很强大,能对其子元素实现多种不同的功能,一个常见的用法就是:给它的一个子元素A设置一个layout_scrollFlags的属性,然后给另外一个子元素B设置一个layout_behavior=”@string/appbar_scrolling_view_behavior”的属性,这个子元素B一般是一个可以滑动的控件,比如RecyclerView、NestedScrollView、FloatingActionButton(默认自带一个layout_behavior属性)等,那么当子元素B滑动的时候,子元素A就会根据其layout_scrollFlags的属性值而做出不同的改变,所以我们要为CollapsingToolbarLayout设置layout_scrollFlags属性。

app:layout_scrollFlags="scroll|exitUntilCollapsed"  
  • scroll - 是否可以滚动。所有想要滑动的控件都要设置这个标志位,如果不设置这个标志位,那么View会固定不动
  • enterAlways - 实现quick return效果,设置了该标志位后,若View已经滑出屏幕,此时手指向下滑,View会立刻出现(比如Toolbar)
  • exitUntilCollapsed - 向上滚动时收缩View,但view可以被固定在顶部(比如Toolbar)
  • enterAlwaysCollapsed - 设置了minHeight时又设置了该标志位的话,你的View只能以最小高度进入,只有当滚动视图到达顶部时才扩大到完整高度。

layout_collapseMode属性

上面提到CollapsingToolbarLayout是一个FrameLayout,它内部能有多个子元素,而子元素也会有不同的表现。比如说,toolbar在缩放后是固定在顶部的,而imageview则是随着布局的滚动而滚动,也即存在一个相对滚动的过程。所以这些子元素可以添加layout_collapseMode标志位进而产生不同的行为。

layout_collapseMode只有两种标志位,分别是: 
  • pin:有该标志位的View在页面滚动的过程中会一直停留在顶部(只有layout_scrollFlags添加exitUntilCollapsed才有效)
  • parallax:有该标志位的View表示能和页面同时滚动。
    与该标志位相关联的一个属性是:视差因子layout_collapseParallaxMultiplier,表示该View与页面的滚动速度存在的差值,造成一种相对滚动的效果。

注意事项
  • 1、Android Design Support Library的使用需要配合特定的主题,一般用AppCompat下的主题即可,也可以自定义主题,继承自AppCompat的主题,否则会报错。另外如果使用Android Studio的话,主题的相关代码需要在styles.xml(v21)文件内做出相应的修改,否则使用Android 5.0以上的机子做测试的话也会报错。
  • 2、由于使用了AppCompat的主题,那么我们的Activity应该继承自AppCompatActivity。
  • 3、笔者之前使用design support library的版本号是23.1.0,在此版本上,CollapsingToolbarLayout没有设置collapsedTitleTextAppearance属性,标题可以正常显示,然而到了24.1.0版本,如果没有设置collapsedTitleTextAppearance属性,则当toolbar收缩后,其标题文字变得非常小。所以我们要设置collapsedTitleTextAppearance=”@style/TextAppearance.AppCompat.Title”这个属性,才能变得正常。
  • 4、如果没有为CollapsingToolbarLayout设置一个title,那么会使用ActionBar自带的标题来显示应用的名称,这是因为调用了setSupportActionBar(toolbar)函数。

样板代码一

添加依赖
compile 'com.android.support:design:25.3.1'
1
1
1
compile 'com.android.support:design:25.3.1'
清单文件中设置
<activity
android:name=".ScrollingActivity"
android:theme="@style/AppTheme.NoActionBar" />
3
3
1
<activity
2
    android:name=".ScrollingActivity"
3
    android:theme="@style/AppTheme.NoActionBar" />
values中新增的主题
<resources>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
8
8
1
<resources>
2
    <style name="AppTheme.NoActionBar">
3
        <item name="windowActionBar">false</item>
4
        <item name="windowNoTitle">true</item>
5
    </style>
6
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
7
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
8
</resources>
values-v21中新增的主题
<resources>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
8
8
1
<resources>
2
    <style name="AppTheme.NoActionBar">
3
        <item name="windowActionBar">false</item>
4
        <item name="windowNoTitle">true</item>
5
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
6
        <item name="android:statusBarColor">@android:color/transparent</item>
7
    </style>
8
</resources>
折叠式工具栏布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.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"
android:fitsSystemWindows="true"> <!--AppBarLayout继承自LinearLayout,其作用就是把其所有子元素当做一个AppBar来使用-->
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="220dp"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay">
<!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景仍旧使用background属性 -->
<!--title:当titleEnable设置为true的时候(默认)显示的可以缩放的标题,不要在Toolbar中设置标题-->
<!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
<!--collapsed/expanded_TitleTextAppearance:折叠/展开之后标题的样式,必须引用另一个资源-->
<!--collapsed/expanded_TitleGravity:折叠/展开之后标题放置的位置,折叠时这里有严重的bug-->
<!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:fitsSystemWindows="true"
app:collapsedTitleGravity="center"
app:collapsedTitleTextAppearance="@style/CollapsedTextStyle"
app:contentScrim="@android:color/holo_orange_dark"
app:expandedTitleGravity="center|bottom"
app:expandedTitleMargin="10dp"
app:expandedTitleTextAppearance="@style/ExpandedTextStyle"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:scrimAnimationDuration="1500"
app:title="可缩放的标题">
<!--pin:有该标志位的View在页面滚动的过程中会一直停留在顶部,只有layout_scrollFlags添加exitUntilCollapsed才有效 -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="40dp"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay"/> <ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:src="@drawable/icon"
app:layout_collapseMode="pin"/> <!--parallax:有该标志位的View表示能和页面同时滚动(默认值),layout_collapseParallaxMultiplier为视差因子 -->
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@android:color/holo_purple"
android:gravity="center"
android:text="和页面同时滚动"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.6"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout> <include layout="@layout/content_scrolling"/> </android.support.design.widget.CoordinatorLayout>
66
66
1
<?xml version="1.0" encoding="utf-8"?>
2
<android.support.design.widget.CoordinatorLayout
3
    xmlns:android="http://schemas.android.com/apk/res/android"
4
    xmlns:app="http://schemas.android.com/apk/res-auto"
5
    android:layout_width="match_parent"
6
    android:layout_height="match_parent"
7
    android:fitsSystemWindows="true">
8

9
    <!--AppBarLayout继承自LinearLayout,其作用就是把其所有子元素当做一个AppBar来使用-->
10
    <android.support.design.widget.AppBarLayout
11
        android:id="@+id/app_bar"
12
        android:layout_width="match_parent"
13
        android:layout_height="220dp"
14
        android:fitsSystemWindows="true"
15
        android:theme="@style/AppTheme.AppBarOverlay">
16
        <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景仍旧使用background属性 -->
17
        <!--title:当titleEnable设置为true的时候(默认)显示的可以缩放的标题,不要在Toolbar中设置标题-->
18
        <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
19
        <!--collapsed/expanded_TitleTextAppearance:折叠/展开之后标题的样式,必须引用另一个资源-->
20
        <!--collapsed/expanded_TitleGravity:折叠/展开之后标题放置的位置,折叠时这里有严重的bug-->
21
        <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
22
        <android.support.design.widget.CollapsingToolbarLayout
23
            android:id="@+id/toolbar_layout"
24
            android:layout_width="match_parent"
25
            android:layout_height="match_parent"
26
            android:background="@drawable/bg"
27
            android:fitsSystemWindows="true"
28
            app:collapsedTitleGravity="center"
29
            app:collapsedTitleTextAppearance="@style/CollapsedTextStyle"
30
            app:contentScrim="@android:color/holo_orange_dark"
31
            app:expandedTitleGravity="center|bottom"
32
            app:expandedTitleMargin="10dp"
33
            app:expandedTitleTextAppearance="@style/ExpandedTextStyle"
34
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
35
            app:scrimAnimationDuration="1500"
36
            app:title="可缩放的标题">
37
            <!--pin:有该标志位的View在页面滚动的过程中会一直停留在顶部,只有layout_scrollFlags添加exitUntilCollapsed才有效 -->
38
            <android.support.v7.widget.Toolbar
39
                android:id="@+id/toolbar"
40
                android:layout_width="match_parent"
41
                android:layout_height="40dp"
42
                app:layout_collapseMode="pin"
43
                app:popupTheme="@style/AppTheme.PopupOverlay"/>
44

45
            <ImageView
46
                android:layout_width="40dp"
47
                android:layout_height="40dp"
48
                android:layout_gravity="center"
49
                android:src="@drawable/icon"
50
                app:layout_collapseMode="pin"/>
51

52
            <!--parallax:有该标志位的View表示能和页面同时滚动(默认值),layout_collapseParallaxMultiplier为视差因子 -->
53
            <TextView
54
                android:layout_width="match_parent"
55
                android:layout_height="20dp"
56
                android:background="@android:color/holo_purple"
57
                android:gravity="center"
58
                android:text="和页面同时滚动"
59
                app:layout_collapseMode="parallax"
60
                app:layout_collapseParallaxMultiplier="0.6"/>
61
        </android.support.design.widget.CollapsingToolbarLayout>
62
    </android.support.design.widget.AppBarLayout>
63

64
    <include layout="@layout/content_scrolling"/>
65

66
</android.support.design.widget.CoordinatorLayout>
内容布局
<?xml version="1.0" encoding="utf-8"?>
<!--内容区域,NestedScrollView和scrollview基本一样,但是它支持嵌套滚动-->
<android.support.v4.widget.NestedScrollView
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="具有丰富项目经验,良好的编程习惯以及较强的学习、适应能力。"/> </android.support.v4.widget.NestedScrollView>
16
16
1
<?xml version="1.0" encoding="utf-8"?>
2
<!--内容区域,NestedScrollView和scrollview基本一样,但是它支持嵌套滚动-->
3
<android.support.v4.widget.NestedScrollView
4
    xmlns:android="http://schemas.android.com/apk/res/android"
5
    xmlns:app="http://schemas.android.com/apk/res-auto"
6
    android:layout_width="match_parent"
7
    android:layout_height="match_parent"
8
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
9

10
    <TextView
11
        android:layout_width="wrap_content"
12
        android:layout_height="wrap_content"
13
        android:layout_margin="16dp"
14
        android:text="具有丰富项目经验,良好的编程习惯以及较强的学习、适应能力。"/>
15

16
</android.support.v4.widget.NestedScrollView>
文字样式
<style name="CollapsedTextStyle">
<item name="android:textSize">20sp</item>
<item name="android:textColor">#00f</item>
</style> <style name="ExpandedTextStyle">
<item name="android:textSize">35sp</item>
<item name="android:textColor">#ff0</item>
</style>
9
9
1
<style name="CollapsedTextStyle">
2
    <item name="android:textSize">20sp</item>
3
    <item name="android:textColor">#00f</item>
4
</style>
5

6
<style name="ExpandedTextStyle">
7
    <item name="android:textSize">35sp</item>
8
    <item name="android:textColor">#ff0</item>
9
</style>

改造

Activity布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@null"
android:fitsSystemWindows="true"> <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null">
<!--设置高度-->
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="300dp"
app:elevation="0dp"> <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景使用background属性 -->
<!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
<!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null"
app:contentScrim="#f0f"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:scrimAnimationDuration="500"> <!-- ==============滑动后折叠的部分,parallax============== -->
<include layout="@layout/content_before"/> <!--pin:有该标志位的View在页面滚动的过程中会一直停留在当前位置,
直到接近CollapsingToolbarLayout的边界时才和其一起滚动。这里是将Toolbar钉在了顶部。
只有CollapsingToolbarLayout的layout_scrollFlags属性添加exitUntilCollapsed时才有效 -->
<!--设置 android:layout_marginLeft="-17dp"可解决不左对齐的bug-->
<!--标题栏-->
<android.support.v7.widget.Toolbar
android:id="@+id/top_toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginLeft="-16dp"
android:background="@null"
app:layout_collapseMode="pin"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:id="@+id/toolbar_tv_title"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text="标题"/>
</RelativeLayout> </android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout> <!-- ==============滑动后展开的部分============== -->
<include layout="@layout/content_aftet"/> </android.support.design.widget.CoordinatorLayout> <!--加载中-->
<RelativeLayout
android:id="@+id/rl_load_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:visibility="gone"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="加载中…"/> </RelativeLayout>
</RelativeLayout>
85
1
<?xml version="1.0" encoding="utf-8"?>
2
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
                xmlns:app="http://schemas.android.com/apk/res-auto"
4
                android:layout_width="match_parent"
5
                android:layout_height="match_parent"
6
                android:background="@null"
7
                android:fitsSystemWindows="true">
8

9
    <android.support.design.widget.CoordinatorLayout
10
        xmlns:android="http://schemas.android.com/apk/res/android"
11
        android:layout_width="match_parent"
12
        android:layout_height="match_parent"
13
        android:background="@null">
14
        <!--设置高度-->
15
        <android.support.design.widget.AppBarLayout
16
            android:id="@+id/app_bar"
17
            android:layout_width="match_parent"
18
            android:layout_height="300dp"
19
            app:elevation="0dp">
20

21
            <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景使用background属性 -->
22
            <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
23
            <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
24
            <android.support.design.widget.CollapsingToolbarLayout
25
                android:layout_width="match_parent"
26
                android:layout_height="match_parent"
27
                android:background="@null"
28
                app:contentScrim="#f0f"
29
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
30
                app:scrimAnimationDuration="500">
31

32
                <!--  ==============滑动后折叠的部分,parallax==============  -->
33
                <include layout="@layout/content_before"/>
34

35
                <!--pin:有该标志位的View在页面滚动的过程中会一直停留在当前位置,
36
                直到接近CollapsingToolbarLayout的边界时才和其一起滚动。这里是将Toolbar钉在了顶部。
37
                只有CollapsingToolbarLayout的layout_scrollFlags属性添加exitUntilCollapsed时才有效 -->
38
                <!--设置 android:layout_marginLeft="-17dp"可解决不左对齐的bug-->
39
                <!--标题栏-->
40
                <android.support.v7.widget.Toolbar
41
                    android:id="@+id/top_toolbar"
42
                    android:layout_width="match_parent"
43
                    android:layout_height="56dp"
44
                    android:layout_marginLeft="-16dp"
45
                    android:background="@null"
46
                    app:layout_collapseMode="pin">
47

48
                    <RelativeLayout
49
                        android:layout_width="match_parent"
50
                        android:layout_height="wrap_content">
51

52
                        <TextView
53
                            android:id="@+id/toolbar_tv_title"
54
                            android:layout_width="match_parent"
55
                            android:layout_height="40dp"
56
                            android:gravity="center_vertical"
57
                            android:text="标题"/>
58
                    </RelativeLayout>
59

60
                </android.support.v7.widget.Toolbar>
61
            </android.support.design.widget.CollapsingToolbarLayout>
62
        </android.support.design.widget.AppBarLayout>
63

64
        <!--  ==============滑动后展开的部分==============  -->
65
        <include layout="@layout/content_aftet"/>
66

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

69
    <!--加载中-->
70
    <RelativeLayout
71
        android:id="@+id/rl_load_view"
72
        android:layout_width="match_parent"
73
        android:layout_height="match_parent"
74
        android:background="#fff"
75
        android:visibility="gone">
76

77
        <TextView
78
            android:layout_width="wrap_content"
79
            android:layout_height="wrap_content"
80
            android:layout_centerInParent="true"
81
            android:gravity="center"
82
            android:text="加载中…"/>
83

84
    </RelativeLayout>
85
</RelativeLayout>
滑动后折叠的部分,content_before
<?xml version="1.0" encoding="utf-8"?>
<!--parallax:有该标志位的View表示能和页面同时滚动(默认值)-->
<!-- 视差因子layout_collapseParallaxMultiplier设为0具有同步滚动效果 -->
<!-- 视差因子layout_collapseParallaxMultiplier设为1具有覆盖效果 -->
<RelativeLayout
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="wrap_content"
android:background="@null"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="1"> <TextView
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="@android:color/holo_green_light"
android:gravity="center"
android:text="滑动后折叠的部分"/> </RelativeLayout>
21
1
<?xml version="1.0" encoding="utf-8"?>
2
<!--parallax:有该标志位的View表示能和页面同时滚动(默认值)-->
3
<!-- 视差因子layout_collapseParallaxMultiplier设为0具有同步滚动效果 -->
4
<!-- 视差因子layout_collapseParallaxMultiplier设为1具有覆盖效果 -->
5
<RelativeLayout
6
    xmlns:android="http://schemas.android.com/apk/res/android"
7
    xmlns:app="http://schemas.android.com/apk/res-auto"
8
    android:layout_width="match_parent"
9
    android:layout_height="wrap_content"
10
    android:background="@null"
11
    app:layout_collapseMode="parallax"
12
    app:layout_collapseParallaxMultiplier="1">
13

14
    <TextView
15
        android:layout_width="match_parent"
16
        android:layout_height="500dp"
17
        android:background="@android:color/holo_green_light"
18
        android:gravity="center"
19
        android:text="滑动后折叠的部分"/>
20

21
</RelativeLayout>
滑动后展开的部分,content_aftet
<?xml version="1.0" encoding="utf-8"?>
<!--系统提供两种layout_behavior,appbar_scrolling_view_behavior和bottom_sheet_behavior-->
<RelativeLayout
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!--最底部的浮窗-->
<TextView
android:id="@+id/tv_bottom"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:gravity="center"
android:text="滑动后展开的部分2"/> <!--用一个ScrollView包住需要滚动的区域,NestedScrollView和支持嵌套滚动-->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/tv_bottom"> <!--ScrollView只能有一个子View-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--内容区域-->
<TextView
android:layout_width="match_parent"
android:layout_height="800dp"
android:background="@android:color/holo_blue_bright"
android:gravity="center"
android:text="滑动后展开的部分1"/> </RelativeLayout> </android.support.v4.widget.NestedScrollView> </RelativeLayout>
42
1
<?xml version="1.0" encoding="utf-8"?>
2
<!--系统提供两种layout_behavior,appbar_scrolling_view_behavior和bottom_sheet_behavior-->
3
<RelativeLayout
4
    xmlns:android="http://schemas.android.com/apk/res/android"
5
    xmlns:app="http://schemas.android.com/apk/res-auto"
6
    android:layout_width="match_parent"
7
    android:layout_height="match_parent"
8
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
9
    <!--最底部的浮窗-->
10
    <TextView
11
        android:id="@+id/tv_bottom"
12
        android:layout_width="match_parent"
13
        android:layout_height="50dp"
14
        android:layout_alignParentBottom="true"
15
        android:background="@color/colorPrimary"
16
        android:gravity="center"
17
        android:text="滑动后展开的部分2"/>
18

19
    <!--用一个ScrollView包住需要滚动的区域,NestedScrollView和支持嵌套滚动-->
20
    <android.support.v4.widget.NestedScrollView
21
        android:layout_width="match_parent"
22
        android:layout_height="wrap_content"
23
        android:layout_above="@+id/tv_bottom">
24

25
        <!--ScrollView只能有一个子View-->
26
        <RelativeLayout
27
            android:layout_width="match_parent"
28
            android:layout_height="wrap_content">
29
            <!--内容区域-->
30
            <TextView
31
                android:layout_width="match_parent"
32
                android:layout_height="800dp"
33
                android:background="@android:color/holo_blue_bright"
34
                android:gravity="center"
35
                android:text="滑动后展开的部分1"/>
36

37
        </RelativeLayout>
38

39
    </android.support.v4.widget.NestedScrollView>
40

41
</RelativeLayout>
42

代码
public class MainActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener, AppBarLayout.OnOffsetChangedListener {
private TextView title;
private AppBarLayout appBar;
private Toolbar toolBar;//android.support.v7.widget.Toolbar private int pxWhenExpanded;
private int maxVerticalOffset; private boolean isAutoScrolling = false;//是否正在自动滚动
private int scrollTo = SCROLL_TO_BOTTOM;//滚动方向
private static final int SCROLL_TO_BOTTOM = 1;//滑动到底部,最初的动作
private static final int SCROLL_TO_TOP = 2;//滑动到顶部,回看的动作 InputManager im; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cl); initview();
initData();
} public void initview() {
title = findViewById(R.id.tv_title);
appBar = findViewById(R.id.app_bar);
toolBar = findViewById(R.id.toolbar);
appBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
appBar.addOnOffsetChangedListener(this);
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
appBar.setExpanded(new Random().nextBoolean(), true);
}
});
} private void initData() {
setSupportActionBar(toolBar);
title.setText("标题是会变的");
pxWhenExpanded = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
} @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
maxVerticalOffset = appBar.getHeight() - toolBar.getHeight() - getStatusBarHeight();
Log.i("bqt", "appBar=" + appBar.getHeight() + ", toolBar=" + toolBar.getHeight() + ", 状态栏=" + getStatusBarHeight());
Log.i("bqt", "maxVerticalOffset=" + maxVerticalOffset);
} @Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//verticalOffset是appBar【当前】高度与【最初】高度的差。最初值是0,向上滑到顶的话值是【-maxVerticalOffset】
Log.i("bqt", "verticalOffset=" + verticalOffset + ", scrollTo=" + scrollTo + ", isAutoScrolling=" + isAutoScrolling);
if (isAutoScrolling) {
if (verticalOffset == 0) {
Log.i("bqt", "【展开了】");
title.setText("展开了");
isAutoScrolling = false;
scrollTo = SCROLL_TO_BOTTOM;
} else if (Math.abs(verticalOffset) == maxVerticalOffset) {
Log.i("bqt", "【折叠了】");
title.setText("折叠了");
isAutoScrolling = false;
scrollTo = SCROLL_TO_TOP;
}
} else {//这一块有bug,不知为什么会往返跳动
if (scrollTo == SCROLL_TO_BOTTOM && Math.abs(verticalOffset) >= pxWhenExpanded) {
Log.i("bqt", "【开始自动折叠】");
appBar.setExpanded(false, true);
isAutoScrolling = true;
} else if (scrollTo == SCROLL_TO_TOP && Math.abs(verticalOffset) <= maxVerticalOffset - pxWhenExpanded) {
Log.i("bqt", "【开始自动展开】");
appBar.setExpanded(true, true);
isAutoScrolling = true;
}
}
} /**
* 状态栏高度,单位px,一般为25dp
*/
private int getStatusBarHeight() {
int height = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
height = getResources().getDimensionPixelSize(resourceId);
}
return height;
} }
95
1
public class MainActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener, AppBarLayout.OnOffsetChangedListener {
2
    private TextView title;
3
    private AppBarLayout appBar;
4
    private Toolbar toolBar;//android.support.v7.widget.Toolbar
5
    
6
    private int pxWhenExpanded;
7
    private int maxVerticalOffset;
8
    
9
    private boolean isAutoScrolling = false;//是否正在自动滚动
10
    private int scrollTo = SCROLL_TO_BOTTOM;//滚动方向
11
    private static final int SCROLL_TO_BOTTOM = 1;//滑动到底部,最初的动作
12
    private static final int SCROLL_TO_TOP = 2;//滑动到顶部,回看的动作
13
    
14
    InputManager im;
15
    
16
    @Override
17
    protected void onCreate(Bundle savedInstanceState) {
18
        super.onCreate(savedInstanceState);
19
        setContentView(R.layout.activity_cl);
20
        
21
        initview();
22
        initData();
23
    }
24
    
25
    public void initview() {
26
        title = findViewById(R.id.tv_title);
27
        appBar = findViewById(R.id.app_bar);
28
        toolBar = findViewById(R.id.toolbar);
29
        appBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
30
        appBar.addOnOffsetChangedListener(this);
31
        title.setOnClickListener(new View.OnClickListener() {
32
            @Override
33
            public void onClick(View v) {
34
                appBar.setExpanded(new Random().nextBoolean(), true);
35
            }
36
        });
37
    }
38
    
39
    private void initData() {
40
        setSupportActionBar(toolBar);
41
        title.setText("标题是会变的");
42
        pxWhenExpanded = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
43
    }
44
    
45
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
46
    @Override
47
    public void onGlobalLayout() {
48
        appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
49
        maxVerticalOffset = appBar.getHeight() - toolBar.getHeight() - getStatusBarHeight();
50
        Log.i("bqt", "appBar=" + appBar.getHeight() + ", toolBar=" + toolBar.getHeight() + ", 状态栏=" + getStatusBarHeight());
51
        Log.i("bqt", "maxVerticalOffset=" + maxVerticalOffset);
52
    }
53
    
54
    @Override
55
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
56
        //verticalOffset是appBar【当前】高度与【最初】高度的差。最初值是0,向上滑到顶的话值是【-maxVerticalOffset】
57
        Log.i("bqt", "verticalOffset=" + verticalOffset + ", scrollTo=" + scrollTo + ", isAutoScrolling=" + isAutoScrolling);
58
        if (isAutoScrolling) {
59
            if (verticalOffset == 0) {
60
                Log.i("bqt", "【展开了】");
61
                title.setText("展开了");
62
                isAutoScrolling = false;
63
                scrollTo = SCROLL_TO_BOTTOM;
64
            } else if (Math.abs(verticalOffset) == maxVerticalOffset) {
65
                Log.i("bqt", "【折叠了】");
66
                title.setText("折叠了");
67
                isAutoScrolling = false;
68
                scrollTo = SCROLL_TO_TOP;
69
            }
70
        } else {//这一块有bug,不知为什么会往返跳动
71
            if (scrollTo == SCROLL_TO_BOTTOM && Math.abs(verticalOffset) >= pxWhenExpanded) {
72
                Log.i("bqt", "【开始自动折叠】");
73
                appBar.setExpanded(false, true);
74
                isAutoScrolling = true;
75
            } else if (scrollTo == SCROLL_TO_TOP && Math.abs(verticalOffset) <= maxVerticalOffset - pxWhenExpanded) {
76
                Log.i("bqt", "【开始自动展开】");
77
                appBar.setExpanded(true, true);
78
                isAutoScrolling = true;
79
            }
80
        }
81
    }
82
    
83
    /**
84
     * 状态栏高度,单位px,一般为25dp
85
     */
86
    private int getStatusBarHeight() {
87
        int height = 0;
88
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
89
        if (resourceId > 0) {
90
            height = getResources().getDimensionPixelSize(resourceId);
91
        }
92
        return height;
93
    }
94
    
95
}
2018-1-9