PS:这是一个超级超级垃圾的控件,强烈建议放弃使用!

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

样板代码一

添加依赖
  1. compile 'com.android.support:design:25.3.1'
1
1
 
1
  1. compile 'com.android.support:design:25.3.1'
清单文件中设置
  1. <activity
  2. android:name=".ScrollingActivity"
  3. android:theme="@style/AppTheme.NoActionBar" />
3
3
 
1
  1. <activity
2
  1.    android:name=".ScrollingActivity"
3
  1.    android:theme="@style/AppTheme.NoActionBar" />
values中新增的主题
  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>
8
8
 
1
  1. <resources>
2
  1.    <style name="AppTheme.NoActionBar">
3
  1.        <item name="windowActionBar">false</item>
4
  1.        <item name="windowNoTitle">true</item>
5
  1.    </style>
6
  1.    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
7
  1.    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
8
  1. </resources>
values-v21中新增的主题
  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>
8
8
 
1
  1. <resources>
2
  1.    <style name="AppTheme.NoActionBar">
3
  1.        <item name="windowActionBar">false</item>
4
  1.        <item name="windowNoTitle">true</item>
5
  1.        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
6
  1.        <item name="android:statusBarColor">@android:color/transparent</item>
7
  1.    </style>
8
  1. </resources>
折叠式工具栏布局
  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. <!--AppBarLayout继承自LinearLayout,其作用就是把其所有子元素当做一个AppBar来使用-->
  9. <android.support.design.widget.AppBarLayout
  10. android:id="@+id/app_bar"
  11. android:layout_width="match_parent"
  12. android:layout_height="220dp"
  13. android:fitsSystemWindows="true"
  14. android:theme="@style/AppTheme.AppBarOverlay">
  15. <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景仍旧使用background属性 -->
  16. <!--title:当titleEnable设置为true的时候(默认)显示的可以缩放的标题,不要在Toolbar中设置标题-->
  17. <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
  18. <!--collapsed/expanded_TitleTextAppearance:折叠/展开之后标题的样式,必须引用另一个资源-->
  19. <!--collapsed/expanded_TitleGravity:折叠/展开之后标题放置的位置,折叠时这里有严重的bug-->
  20. <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
  21. <android.support.design.widget.CollapsingToolbarLayout
  22. android:id="@+id/toolbar_layout"
  23. android:layout_width="match_parent"
  24. android:layout_height="match_parent"
  25. android:background="@drawable/bg"
  26. android:fitsSystemWindows="true"
  27. app:collapsedTitleGravity="center"
  28. app:collapsedTitleTextAppearance="@style/CollapsedTextStyle"
  29. app:contentScrim="@android:color/holo_orange_dark"
  30. app:expandedTitleGravity="center|bottom"
  31. app:expandedTitleMargin="10dp"
  32. app:expandedTitleTextAppearance="@style/ExpandedTextStyle"
  33. app:layout_scrollFlags="scroll|exitUntilCollapsed"
  34. app:scrimAnimationDuration="1500"
  35. app:title="可缩放的标题">
  36. <!--pin:有该标志位的View在页面滚动的过程中会一直停留在顶部,只有layout_scrollFlags添加exitUntilCollapsed才有效 -->
  37. <android.support.v7.widget.Toolbar
  38. android:id="@+id/toolbar"
  39. android:layout_width="match_parent"
  40. android:layout_height="40dp"
  41. app:layout_collapseMode="pin"
  42. app:popupTheme="@style/AppTheme.PopupOverlay"/>
  43. <ImageView
  44. android:layout_width="40dp"
  45. android:layout_height="40dp"
  46. android:layout_gravity="center"
  47. android:src="@drawable/icon"
  48. app:layout_collapseMode="pin"/>
  49. <!--parallax:有该标志位的View表示能和页面同时滚动(默认值),layout_collapseParallaxMultiplier为视差因子 -->
  50. <TextView
  51. android:layout_width="match_parent"
  52. android:layout_height="20dp"
  53. android:background="@android:color/holo_purple"
  54. android:gravity="center"
  55. android:text="和页面同时滚动"
  56. app:layout_collapseMode="parallax"
  57. app:layout_collapseParallaxMultiplier="0.6"/>
  58. </android.support.design.widget.CollapsingToolbarLayout>
  59. </android.support.design.widget.AppBarLayout>
  60. <include layout="@layout/content_scrolling"/>
  61. </android.support.design.widget.CoordinatorLayout>
66
66
 
1
  1. <?xml version="1.0" encoding="utf-8"?>
2
  1. <android.support.design.widget.CoordinatorLayout
3
  1.    xmlns:android="http://schemas.android.com/apk/res/android"
4
  1.    xmlns:app="http://schemas.android.com/apk/res-auto"
5
  1.    android:layout_width="match_parent"
6
  1.    android:layout_height="match_parent"
7
  1.    android:fitsSystemWindows="true">
8
  1.  
9
  1.    <!--AppBarLayout继承自LinearLayout,其作用就是把其所有子元素当做一个AppBar来使用-->
10
  1.    <android.support.design.widget.AppBarLayout
11
  1.        android:id="@+id/app_bar"
12
  1.        android:layout_width="match_parent"
13
  1.        android:layout_height="220dp"
14
  1.        android:fitsSystemWindows="true"
15
  1.        android:theme="@style/AppTheme.AppBarOverlay">
16
  1.        <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景仍旧使用background属性 -->
17
  1.        <!--title:当titleEnable设置为true的时候(默认)显示的可以缩放的标题,不要在Toolbar中设置标题-->
18
  1.        <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
19
  1.        <!--collapsed/expanded_TitleTextAppearance:折叠/展开之后标题的样式,必须引用另一个资源-->
20
  1.        <!--collapsed/expanded_TitleGravity:折叠/展开之后标题放置的位置,折叠时这里有严重的bug-->
21
  1.        <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
22
  1.        <android.support.design.widget.CollapsingToolbarLayout
23
  1.            android:id="@+id/toolbar_layout"
24
  1.            android:layout_width="match_parent"
25
  1.            android:layout_height="match_parent"
26
  1.            android:background="@drawable/bg"
27
  1.            android:fitsSystemWindows="true"
28
  1.            app:collapsedTitleGravity="center"
29
  1.            app:collapsedTitleTextAppearance="@style/CollapsedTextStyle"
30
  1.            app:contentScrim="@android:color/holo_orange_dark"
31
  1.            app:expandedTitleGravity="center|bottom"
32
  1.            app:expandedTitleMargin="10dp"
33
  1.            app:expandedTitleTextAppearance="@style/ExpandedTextStyle"
34
  1.            app:layout_scrollFlags="scroll|exitUntilCollapsed"
35
  1.            app:scrimAnimationDuration="1500"
36
  1.            app:title="可缩放的标题">
37
  1.            <!--pin:有该标志位的View在页面滚动的过程中会一直停留在顶部,只有layout_scrollFlags添加exitUntilCollapsed才有效 -->
38
  1.            <android.support.v7.widget.Toolbar
39
  1.                android:id="@+id/toolbar"
40
  1.                android:layout_width="match_parent"
41
  1.                android:layout_height="40dp"
42
  1.                app:layout_collapseMode="pin"
43
  1.                app:popupTheme="@style/AppTheme.PopupOverlay"/>
44
  1.  
45
  1.            <ImageView
46
  1.                android:layout_width="40dp"
47
  1.                android:layout_height="40dp"
48
  1.                android:layout_gravity="center"
49
  1.                android:src="@drawable/icon"
50
  1.                app:layout_collapseMode="pin"/>
51
  1.  
52
  1.            <!--parallax:有该标志位的View表示能和页面同时滚动(默认值),layout_collapseParallaxMultiplier为视差因子 -->
53
  1.            <TextView
54
  1.                android:layout_width="match_parent"
55
  1.                android:layout_height="20dp"
56
  1.                android:background="@android:color/holo_purple"
57
  1.                android:gravity="center"
58
  1.                android:text="和页面同时滚动"
59
  1.                app:layout_collapseMode="parallax"
60
  1.                app:layout_collapseParallaxMultiplier="0.6"/>
61
  1.        </android.support.design.widget.CollapsingToolbarLayout>
62
  1.    </android.support.design.widget.AppBarLayout>
63
  1.  
64
  1.    <include layout="@layout/content_scrolling"/>
65
  1.  
66
  1. </android.support.design.widget.CoordinatorLayout>
内容布局
  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. <TextView
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_margin="16dp"
  13. android:text="具有丰富项目经验,良好的编程习惯以及较强的学习、适应能力。"/>
  14. </android.support.v4.widget.NestedScrollView>
16
16
 
1
  1. <?xml version="1.0" encoding="utf-8"?>
2
  1. <!--内容区域,NestedScrollView和scrollview基本一样,但是它支持嵌套滚动-->
3
  1. <android.support.v4.widget.NestedScrollView
4
  1.    xmlns:android="http://schemas.android.com/apk/res/android"
5
  1.    xmlns:app="http://schemas.android.com/apk/res-auto"
6
  1.    android:layout_width="match_parent"
7
  1.    android:layout_height="match_parent"
8
  1.    app:layout_behavior="@string/appbar_scrolling_view_behavior">
9
  1.  
10
  1.    <TextView
11
  1.        android:layout_width="wrap_content"
12
  1.        android:layout_height="wrap_content"
13
  1.        android:layout_margin="16dp"
14
  1.        android:text="具有丰富项目经验,良好的编程习惯以及较强的学习、适应能力。"/>
15
  1.  
16
  1. </android.support.v4.widget.NestedScrollView>
文字样式
  1. <style name="CollapsedTextStyle">
  2. <item name="android:textSize">20sp</item>
  3. <item name="android:textColor">#00f</item>
  4. </style>
  5. <style name="ExpandedTextStyle">
  6. <item name="android:textSize">35sp</item>
  7. <item name="android:textColor">#ff0</item>
  8. </style>
9
9
 
1
  1. <style name="CollapsedTextStyle">
2
  1. <item name="android:textSize">20sp</item>
3
  1. <item name="android:textColor">#00f</item>
4
  1. </style>
5
  1.  
6
  1. <style name="ExpandedTextStyle">
7
  1. <item name="android:textSize">35sp</item>
8
  1. <item name="android:textColor">#ff0</item>
9
  1. </style>

改造

Activity布局
  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. <android.support.design.widget.CoordinatorLayout
  9. xmlns:android="http://schemas.android.com/apk/res/android"
  10. android:layout_width="match_parent"
  11. android:layout_height="match_parent"
  12. android:background="@null">
  13. <!--设置高度-->
  14. <android.support.design.widget.AppBarLayout
  15. android:id="@+id/app_bar"
  16. android:layout_width="match_parent"
  17. android:layout_height="300dp"
  18. app:elevation="0dp">
  19. <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景使用background属性 -->
  20. <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
  21. <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
  22. <android.support.design.widget.CollapsingToolbarLayout
  23. android:layout_width="match_parent"
  24. android:layout_height="match_parent"
  25. android:background="@null"
  26. app:contentScrim="#f0f"
  27. app:layout_scrollFlags="scroll|exitUntilCollapsed"
  28. app:scrimAnimationDuration="500">
  29. <!-- ==============滑动后折叠的部分,parallax============== -->
  30. <include layout="@layout/content_before"/>
  31. <!--pin:有该标志位的View在页面滚动的过程中会一直停留在当前位置,
  32. 直到接近CollapsingToolbarLayout的边界时才和其一起滚动。这里是将Toolbar钉在了顶部。
  33. 只有CollapsingToolbarLayout的layout_scrollFlags属性添加exitUntilCollapsed时才有效 -->
  34. <!--设置 android:layout_marginLeft="-17dp"可解决不左对齐的bug-->
  35. <!--标题栏-->
  36. <android.support.v7.widget.Toolbar
  37. android:id="@+id/top_toolbar"
  38. android:layout_width="match_parent"
  39. android:layout_height="56dp"
  40. android:layout_marginLeft="-16dp"
  41. android:background="@null"
  42. app:layout_collapseMode="pin">
  43. <RelativeLayout
  44. android:layout_width="match_parent"
  45. android:layout_height="wrap_content">
  46. <TextView
  47. android:id="@+id/toolbar_tv_title"
  48. android:layout_width="match_parent"
  49. android:layout_height="40dp"
  50. android:gravity="center_vertical"
  51. android:text="标题"/>
  52. </RelativeLayout>
  53. </android.support.v7.widget.Toolbar>
  54. </android.support.design.widget.CollapsingToolbarLayout>
  55. </android.support.design.widget.AppBarLayout>
  56. <!-- ==============滑动后展开的部分============== -->
  57. <include layout="@layout/content_aftet"/>
  58. </android.support.design.widget.CoordinatorLayout>
  59. <!--加载中-->
  60. <RelativeLayout
  61. android:id="@+id/rl_load_view"
  62. android:layout_width="match_parent"
  63. android:layout_height="match_parent"
  64. android:background="#fff"
  65. android:visibility="gone">
  66. <TextView
  67. android:layout_width="wrap_content"
  68. android:layout_height="wrap_content"
  69. android:layout_centerInParent="true"
  70. android:gravity="center"
  71. android:text="加载中…"/>
  72. </RelativeLayout>
  73. </RelativeLayout>
85
 
1
  1. <?xml version="1.0" encoding="utf-8"?>
2
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
  1.                xmlns:app="http://schemas.android.com/apk/res-auto"
4
  1.                android:layout_width="match_parent"
5
  1.                android:layout_height="match_parent"
6
  1.                android:background="@null"
7
  1.                android:fitsSystemWindows="true">
8
  1.  
9
  1.    <android.support.design.widget.CoordinatorLayout
10
  1.        xmlns:android="http://schemas.android.com/apk/res/android"
11
  1.        android:layout_width="match_parent"
12
  1.        android:layout_height="match_parent"
13
  1.        android:background="@null">
14
  1.        <!--设置高度-->
15
  1.        <android.support.design.widget.AppBarLayout
16
  1.            android:id="@+id/app_bar"
17
  1.            android:layout_width="match_parent"
18
  1.            android:layout_height="300dp"
19
  1.            app:elevation="0dp">
20
  1.  
21
  1.            <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景使用background属性 -->
22
  1.            <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
23
  1.            <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
24
  1.            <android.support.design.widget.CollapsingToolbarLayout
25
  1.                android:layout_width="match_parent"
26
  1.                android:layout_height="match_parent"
27
  1.                android:background="@null"
28
  1.                app:contentScrim="#f0f"
29
  1.                app:layout_scrollFlags="scroll|exitUntilCollapsed"
30
  1.                app:scrimAnimationDuration="500">
31
  1.  
32
  1.                <!-- ==============滑动后折叠的部分,parallax============== -->
33
  1.                <include layout="@layout/content_before"/>
34
  1.  
35
  1.                <!--pin:有该标志位的View在页面滚动的过程中会一直停留在当前位置,
36
  1.                直到接近CollapsingToolbarLayout的边界时才和其一起滚动。这里是将Toolbar钉在了顶部。
37
  1.                只有CollapsingToolbarLayoutlayout_scrollFlags属性添加exitUntilCollapsed时才有效 -->
38
  1.                <!--设置 android:layout_marginLeft="-17dp"可解决不左对齐的bug-->
39
  1.                <!--标题栏-->
40
  1.                <android.support.v7.widget.Toolbar
41
  1.                    android:id="@+id/top_toolbar"
42
  1.                    android:layout_width="match_parent"
43
  1.                    android:layout_height="56dp"
44
  1.                    android:layout_marginLeft="-16dp"
45
  1.                    android:background="@null"
46
  1.                    app:layout_collapseMode="pin">
47
  1.  
48
  1.                    <RelativeLayout
49
  1.                        android:layout_width="match_parent"
50
  1.                        android:layout_height="wrap_content">
51
  1.  
52
  1.                        <TextView
53
  1.                            android:id="@+id/toolbar_tv_title"
54
  1.                            android:layout_width="match_parent"
55
  1.                            android:layout_height="40dp"
56
  1.                            android:gravity="center_vertical"
57
  1.                            android:text="标题"/>
58
  1.                    </RelativeLayout>
59
  1.  
60
  1.                </android.support.v7.widget.Toolbar>
61
  1.            </android.support.design.widget.CollapsingToolbarLayout>
62
  1.        </android.support.design.widget.AppBarLayout>
63
  1.  
64
  1.        <!-- ==============滑动后展开的部分============== -->
65
  1.        <include layout="@layout/content_aftet"/>
66
  1.  
67
  1.    </android.support.design.widget.CoordinatorLayout>
68
  1.  
69
  1.    <!--加载中-->
70
  1.    <RelativeLayout
71
  1.        android:id="@+id/rl_load_view"
72
  1.        android:layout_width="match_parent"
73
  1.        android:layout_height="match_parent"
74
  1.        android:background="#fff"
75
  1.        android:visibility="gone">
76
  1.  
77
  1.        <TextView
78
  1.            android:layout_width="wrap_content"
79
  1.            android:layout_height="wrap_content"
80
  1.            android:layout_centerInParent="true"
81
  1.            android:gravity="center"
82
  1.            android:text="加载中…"/>
83
  1.  
84
  1.    </RelativeLayout>
85
  1. </RelativeLayout>
滑动后折叠的部分,content_before
  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. <TextView
  14. android:layout_width="match_parent"
  15. android:layout_height="500dp"
  16. android:background="@android:color/holo_green_light"
  17. android:gravity="center"
  18. android:text="滑动后折叠的部分"/>
  19. </RelativeLayout>
21
 
1
  1. <?xml version="1.0" encoding="utf-8"?>
2
  1. <!--parallax:有该标志位的View表示能和页面同时滚动(默认值)-->
3
  1. <!-- 视差因子layout_collapseParallaxMultiplier设为0具有同步滚动效果 -->
4
  1. <!-- 视差因子layout_collapseParallaxMultiplier设为1具有覆盖效果 -->
5
  1. <RelativeLayout
6
  1.    xmlns:android="http://schemas.android.com/apk/res/android"
7
  1.    xmlns:app="http://schemas.android.com/apk/res-auto"
8
  1.    android:layout_width="match_parent"
9
  1.    android:layout_height="wrap_content"
10
  1.    android:background="@null"
11
  1.    app:layout_collapseMode="parallax"
12
  1.    app:layout_collapseParallaxMultiplier="1">
13
  1.  
14
  1.    <TextView
15
  1.        android:layout_width="match_parent"
16
  1.        android:layout_height="500dp"
17
  1.        android:background="@android:color/holo_green_light"
18
  1.        android:gravity="center"
19
  1.        android:text="滑动后折叠的部分"/>
20
  1.  
21
  1. </RelativeLayout>
滑动后展开的部分,content_aftet
  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. <!--用一个ScrollView包住需要滚动的区域,NestedScrollView和支持嵌套滚动-->
  19. <android.support.v4.widget.NestedScrollView
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:layout_above="@+id/tv_bottom">
  23. <!--ScrollView只能有一个子View-->
  24. <RelativeLayout
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content">
  27. <!--内容区域-->
  28. <TextView
  29. android:layout_width="match_parent"
  30. android:layout_height="800dp"
  31. android:background="@android:color/holo_blue_bright"
  32. android:gravity="center"
  33. android:text="滑动后展开的部分1"/>
  34. </RelativeLayout>
  35. </android.support.v4.widget.NestedScrollView>
  36. </RelativeLayout>
42
 
1
  1. <?xml version="1.0" encoding="utf-8"?>
2
  1. <!--系统提供两种layout_behavior,appbar_scrolling_view_behavior和bottom_sheet_behavior-->
3
  1. <RelativeLayout
4
  1.    xmlns:android="http://schemas.android.com/apk/res/android"
5
  1.    xmlns:app="http://schemas.android.com/apk/res-auto"
6
  1.    android:layout_width="match_parent"
7
  1.    android:layout_height="match_parent"
8
  1.    app:layout_behavior="@string/appbar_scrolling_view_behavior">
9
  1.    <!--最底部的浮窗-->
10
  1.    <TextView
11
  1.        android:id="@+id/tv_bottom"
12
  1.        android:layout_width="match_parent"
13
  1.        android:layout_height="50dp"
14
  1.        android:layout_alignParentBottom="true"
15
  1.        android:background="@color/colorPrimary"
16
  1.        android:gravity="center"
17
  1.        android:text="滑动后展开的部分2"/>
18
  1.  
19
  1.    <!--用一个ScrollView包住需要滚动的区域,NestedScrollView和支持嵌套滚动-->
20
  1.    <android.support.v4.widget.NestedScrollView
21
  1.        android:layout_width="match_parent"
22
  1.        android:layout_height="wrap_content"
23
  1.        android:layout_above="@+id/tv_bottom">
24
  1.  
25
  1.        <!--ScrollView只能有一个子View-->
26
  1.        <RelativeLayout
27
  1.            android:layout_width="match_parent"
28
  1.            android:layout_height="wrap_content">
29
  1.            <!--内容区域-->
30
  1.            <TextView
31
  1.                android:layout_width="match_parent"
32
  1.                android:layout_height="800dp"
33
  1.                android:background="@android:color/holo_blue_bright"
34
  1.                android:gravity="center"
35
  1.                android:text="滑动后展开的部分1"/>
36
  1.  
37
  1.        </RelativeLayout>
38
  1.  
39
  1.    </android.support.v4.widget.NestedScrollView>
40
  1.  
41
  1. </RelativeLayout>
42
  1.  
代码
  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. private int pxWhenExpanded;
  6. private int maxVerticalOffset;
  7. private boolean isAutoScrolling = false;//是否正在自动滚动
  8. private int scrollTo = SCROLL_TO_BOTTOM;//滚动方向
  9. private static final int SCROLL_TO_BOTTOM = 1;//滑动到底部,最初的动作
  10. private static final int SCROLL_TO_TOP = 2;//滑动到顶部,回看的动作
  11. InputManager im;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_cl);
  16. initview();
  17. initData();
  18. }
  19. public void initview() {
  20. title = findViewById(R.id.tv_title);
  21. appBar = findViewById(R.id.app_bar);
  22. toolBar = findViewById(R.id.toolbar);
  23. appBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
  24. appBar.addOnOffsetChangedListener(this);
  25. title.setOnClickListener(new View.OnClickListener() {
  26. @Override
  27. public void onClick(View v) {
  28. appBar.setExpanded(new Random().nextBoolean(), true);
  29. }
  30. });
  31. }
  32. private void initData() {
  33. setSupportActionBar(toolBar);
  34. title.setText("标题是会变的");
  35. pxWhenExpanded = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
  36. }
  37. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  38. @Override
  39. public void onGlobalLayout() {
  40. appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  41. maxVerticalOffset = appBar.getHeight() - toolBar.getHeight() - getStatusBarHeight();
  42. Log.i("bqt", "appBar=" + appBar.getHeight() + ", toolBar=" + toolBar.getHeight() + ", 状态栏=" + getStatusBarHeight());
  43. Log.i("bqt", "maxVerticalOffset=" + maxVerticalOffset);
  44. }
  45. @Override
  46. public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
  47. //verticalOffset是appBar【当前】高度与【最初】高度的差。最初值是0,向上滑到顶的话值是【-maxVerticalOffset】
  48. Log.i("bqt", "verticalOffset=" + verticalOffset + ", scrollTo=" + scrollTo + ", isAutoScrolling=" + isAutoScrolling);
  49. if (isAutoScrolling) {
  50. if (verticalOffset == 0) {
  51. Log.i("bqt", "【展开了】");
  52. title.setText("展开了");
  53. isAutoScrolling = false;
  54. scrollTo = SCROLL_TO_BOTTOM;
  55. } else if (Math.abs(verticalOffset) == maxVerticalOffset) {
  56. Log.i("bqt", "【折叠了】");
  57. title.setText("折叠了");
  58. isAutoScrolling = false;
  59. scrollTo = SCROLL_TO_TOP;
  60. }
  61. } else {//这一块有bug,不知为什么会往返跳动
  62. if (scrollTo == SCROLL_TO_BOTTOM && Math.abs(verticalOffset) >= pxWhenExpanded) {
  63. Log.i("bqt", "【开始自动折叠】");
  64. appBar.setExpanded(false, true);
  65. isAutoScrolling = true;
  66. } else if (scrollTo == SCROLL_TO_TOP && Math.abs(verticalOffset) <= maxVerticalOffset - pxWhenExpanded) {
  67. Log.i("bqt", "【开始自动展开】");
  68. appBar.setExpanded(true, true);
  69. isAutoScrolling = true;
  70. }
  71. }
  72. }
  73. /**
  74. * 状态栏高度,单位px,一般为25dp
  75. */
  76. private int getStatusBarHeight() {
  77. int height = 0;
  78. int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
  79. if (resourceId > 0) {
  80. height = getResources().getDimensionPixelSize(resourceId);
  81. }
  82. return height;
  83. }
  84. }
95
 
1
  1. public class MainActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener, AppBarLayout.OnOffsetChangedListener {
2
  1. private TextView title;
3
  1. private AppBarLayout appBar;
4
  1. private Toolbar toolBar;//android.support.v7.widget.Toolbar
5
6
  1. private int pxWhenExpanded;
7
  1. private int maxVerticalOffset;
8
9
  1. private boolean isAutoScrolling = false;//是否正在自动滚动
10
  1. private int scrollTo = SCROLL_TO_BOTTOM;//滚动方向
11
  1. private static final int SCROLL_TO_BOTTOM = 1;//滑动到底部,最初的动作
12
  1. private static final int SCROLL_TO_TOP = 2;//滑动到顶部,回看的动作
13
14
  1. InputManager im;
15
16
  1. @Override
17
  1. protected void onCreate(Bundle savedInstanceState) {
18
  1. super.onCreate(savedInstanceState);
19
  1. setContentView(R.layout.activity_cl);
20
21
  1. initview();
22
  1. initData();
23
  1. }
24
25
  1. public void initview() {
26
  1. title = findViewById(R.id.tv_title);
27
  1. appBar = findViewById(R.id.app_bar);
28
  1. toolBar = findViewById(R.id.toolbar);
29
  1. appBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
30
  1. appBar.addOnOffsetChangedListener(this);
31
  1. title.setOnClickListener(new View.OnClickListener() {
32
  1. @Override
33
  1. public void onClick(View v) {
34
  1. appBar.setExpanded(new Random().nextBoolean(), true);
35
  1. }
36
  1. });
37
  1. }
38
39
  1. private void initData() {
40
  1. setSupportActionBar(toolBar);
41
  1. title.setText("标题是会变的");
42
  1. pxWhenExpanded = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
43
  1. }
44
45
  1. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
46
  1. @Override
47
  1. public void onGlobalLayout() {
48
  1. appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
49
  1. maxVerticalOffset = appBar.getHeight() - toolBar.getHeight() - getStatusBarHeight();
50
  1. Log.i("bqt", "appBar=" + appBar.getHeight() + ", toolBar=" + toolBar.getHeight() + ", 状态栏=" + getStatusBarHeight());
51
  1. Log.i("bqt", "maxVerticalOffset=" + maxVerticalOffset);
52
  1. }
53
54
  1. @Override
55
  1. public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
56
  1. //verticalOffset是appBar【当前】高度与【最初】高度的差。最初值是0,向上滑到顶的话值是【-maxVerticalOffset】
57
  1. Log.i("bqt", "verticalOffset=" + verticalOffset + ", scrollTo=" + scrollTo + ", isAutoScrolling=" + isAutoScrolling);
58
  1. if (isAutoScrolling) {
59
  1. if (verticalOffset == 0) {
60
  1. Log.i("bqt", "【展开了】");
61
  1. title.setText("展开了");
62
  1. isAutoScrolling = false;
63
  1. scrollTo = SCROLL_TO_BOTTOM;
64
  1. } else if (Math.abs(verticalOffset) == maxVerticalOffset) {
65
  1. Log.i("bqt", "【折叠了】");
66
  1. title.setText("折叠了");
67
  1. isAutoScrolling = false;
68
  1. scrollTo = SCROLL_TO_TOP;
69
  1. }
70
  1. } else {//这一块有bug,不知为什么会往返跳动
71
  1. if (scrollTo == SCROLL_TO_BOTTOM && Math.abs(verticalOffset) >= pxWhenExpanded) {
72
  1. Log.i("bqt", "【开始自动折叠】");
73
  1. appBar.setExpanded(false, true);
74
  1. isAutoScrolling = true;
75
  1. } else if (scrollTo == SCROLL_TO_TOP && Math.abs(verticalOffset) <= maxVerticalOffset - pxWhenExpanded) {
76
  1. Log.i("bqt", "【开始自动展开】");
77
  1. appBar.setExpanded(true, true);
78
  1. isAutoScrolling = true;
79
  1. }
80
  1. }
81
  1. }
82
83
  1. /**
84
  1. * 状态栏高度,单位px,一般为25dp
85
  1. */
86
  1. private int getStatusBarHeight() {
87
  1. int height = 0;
88
  1. int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
89
  1. if (resourceId > 0) {
90
  1. height = getResources().getDimensionPixelSize(resourceId);
91
  1. }
92
  1. return height;
93
  1. }
94
95
  1. }
2018-1-9

折叠伸缩工具栏 CollapsingToolbarLayout的更多相关文章

  1. CoordinatorLayout-带图片伸缩工具栏

    伸缩工具栏toolbardesign 效果图: 步骤一: 在build.gilde中添加以下代码 dependencies { compile fileTree(dir: 'libs', includ ...

  2. 【转】Material Design 折叠效果 Toolbar CollapsingToolbarLayout AppBarLayout

    我非常喜欢Material Design里折叠工具栏的效果,bilibili Android客户端视频详情页就是采用的这种设计.这篇文章的第二部分我们就通过简单的模仿bilibili视频详情页的实现来 ...

  3. Android CollapsingToolbarLayout使用介绍

    我非常喜欢Material Design里折叠工具栏的效果,bilibili Android客户端视频详情页就是采用的这种设计.这篇文章的第二部分我们就通过简单的模仿bilibili视频详情页的实现来 ...

  4. Android开发实战之拥有Material Design风格的折叠布局

    关于折叠布局,也许你并不陌生,最新版的陌陌,或者一些其他的社交APP都有一个折叠布局.折叠布局,让我们的APP更加具有交互性,同时也更加美观,先来展示一下效果图: 这是我个人做的一个APP主界面,可以 ...

  5. 一个Activity掌握Design新控件 (转)

    原文地址:http://blog.csdn.net/lavor_zl/article/details/51295364 谷歌在推出Android5.0的同时推出了全新的设计Material Desig ...

  6. CollapsingToolbarLayoutDemo【可折叠式标题栏,顺便带有CardView卡片式布局】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 CollapsingToolBarLayout是一个作用于ToolBar基础之上的布局,它也是由Design Support库提供的 ...

  7. CoordinatorLayout使用全解析

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u012124438/article/details/56701641 CoordinatorLayo ...

  8. Android support library支持包常用控件介绍(一)

    谷歌官方推出Material Design 设计理念已经有段时间了,为支持更方便的实现Material Design设计效果,官方给出了Android support design library 支 ...

  9. Bootstraptable源码

    // @author 文志新 http://jsfiddle.net/wenyi/47nz7ez9/3/ /**关于插件的通用构造 * * 构造函数PluginName($trigger,option ...

随机推荐

  1. loadrunner中controller 中scenario-> rendezvous灰色不可用的解决方法:

    1.首先确保lr_rendezvous("login");函数添加成功  Action() { web_set_max_html_param_len("2048" ...

  2. Group_Concat函数示例

    1. 函数定义: GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [AS ...

  3. 转:perl源码审计

    转:http://www.cgisecurity.com/lib/sips.html Security Issues in Perl Scripts By Jordan Dimov (jdimov@c ...

  4. Screen 常用命令+VNC 启动停止命令总结

    screen -S 名称:创建一个新的会话 screen -r 会话ID:恢复一个Detach状态的会话 screen -xr 会话ID:强制恢复一个Attach状态的会话,常用于掉线时上次的会话没有 ...

  5. EOJ 3246 实验室传染病

    线段树,暴力. 先处理出每个点直接能感染到的最左边的和最右边的. 之后每次扩展,看向左能到达的那些点中,最左以及最右能到哪些点,更新. 看向右能到达的那些点中,最左以及最右能到哪些点,更新. 最左最右 ...

  6. Spring框架 AOP面向切面编程(转)

    一.前言 在以前的项目中,很少去关注spring aop的具体实现与理论,只是简单了解了一下什么是aop具体怎么用,看到了一篇博文写得还不错,就转载来学习一下,博文地址:http://www.cnbl ...

  7. EAP-MD5认证暴力破解工具eapmd5pass

    EAP-MD5认证暴力破解工具eapmd5pass   EAP-MD5是一种基于802.1x协议的认证机制.由于该机制存在漏洞,所以并不能保证数据安全.Kali Linux预置一个专用工具eapmd5 ...

  8. 简单DP+暴力 POJ 1050

    To the Max Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 45915   Accepted: 24282 Desc ...

  9. 移动应用安全开发指南(Android)--完结篇

    如果IE显示格式不正常,请使用chrome浏览器 1.认证和授权 概述 认证是用来证明用户身份合法性的过程,授权是用来证明用户可以合法地做哪些事的过程,这两个过程一般是在服务器端执行的,但也有的APP ...

  10. Handling Errors and Exceptions

    http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...