折叠伸缩工具栏 CollapsingToolbarLayout
Android沉浸式效果的实现,状态栏和导航栏均支持设置颜色、渐变色、图片、透明度、内容入侵和状态栏深色字体;兼容竖屏、横屏,当屏幕旋转时会自动适配。Android沉浸式效果的实现,状态栏和导航栏均支持设置颜色、渐变色、图片、透明度、内容入侵和状态栏深色字体;兼容竖屏、横屏,当屏幕旋转时会自动适配。
简介
常用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)函数。
- 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
- scroll - 是否可以滚动。所有想要滑动的控件都要设置这个标志位,如果不设置这个标志位,那么View会固定不动
- enterAlways - 实现quick return效果,设置了该标志位后,若View已经滑出屏幕,此时手指向下滑,View会立刻出现(比如Toolbar)
- exitUntilCollapsed - 向上滚动时收缩View,但view可以被固定在顶部(比如Toolbar)
- enterAlwaysCollapsed - 设置了minHeight时又设置了该标志位的话,你的View只能以最小高度进入,只有当滚动视图到达顶部时才扩大到完整高度。
- 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'compile 'com.android.support:design:25.3.1'
<activity
    android:name=".ScrollingActivity"
    android:theme="@style/AppTheme.NoActionBar" /><activity
android:name=".ScrollingActivity"
android:theme="@style/AppTheme.NoActionBar" />
<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><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>
<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><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>
<?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><?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>
<?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><?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>
<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><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>
改造
<?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><?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>
<?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><?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>
<?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>
<?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>
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;
	}
}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;
}
}
折叠伸缩工具栏 CollapsingToolbarLayout的更多相关文章
- CoordinatorLayout-带图片伸缩工具栏
		伸缩工具栏toolbardesign 效果图: 步骤一: 在build.gilde中添加以下代码 dependencies { compile fileTree(dir: 'libs', includ ... 
- 【转】Material Design 折叠效果 Toolbar CollapsingToolbarLayout AppBarLayout
		我非常喜欢Material Design里折叠工具栏的效果,bilibili Android客户端视频详情页就是采用的这种设计.这篇文章的第二部分我们就通过简单的模仿bilibili视频详情页的实现来 ... 
- Android CollapsingToolbarLayout使用介绍
		我非常喜欢Material Design里折叠工具栏的效果,bilibili Android客户端视频详情页就是采用的这种设计.这篇文章的第二部分我们就通过简单的模仿bilibili视频详情页的实现来 ... 
- Android开发实战之拥有Material Design风格的折叠布局
		关于折叠布局,也许你并不陌生,最新版的陌陌,或者一些其他的社交APP都有一个折叠布局.折叠布局,让我们的APP更加具有交互性,同时也更加美观,先来展示一下效果图: 这是我个人做的一个APP主界面,可以 ... 
- 一个Activity掌握Design新控件 (转)
		原文地址:http://blog.csdn.net/lavor_zl/article/details/51295364 谷歌在推出Android5.0的同时推出了全新的设计Material Desig ... 
- CollapsingToolbarLayoutDemo【可折叠式标题栏,顺便带有CardView卡片式布局】
		版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 CollapsingToolBarLayout是一个作用于ToolBar基础之上的布局,它也是由Design Support库提供的 ... 
- CoordinatorLayout使用全解析
		版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u012124438/article/details/56701641 CoordinatorLayo ... 
- Android support library支持包常用控件介绍(一)
		谷歌官方推出Material Design 设计理念已经有段时间了,为支持更方便的实现Material Design设计效果,官方给出了Android support design library 支 ... 
- Bootstraptable源码
		// @author 文志新 http://jsfiddle.net/wenyi/47nz7ez9/3/ /**关于插件的通用构造 * * 构造函数PluginName($trigger,option ... 
随机推荐
- 洛谷P3459 [POI2007]MEG-Megalopolis [树链剖分]
			题目传送门 MEG 题目描述 Byteotia has been eventually touched by globalisation, and so has Byteasar the Postma ... 
- Redux学习之解读applyMiddleware源码深入middleware工作机制
			随笔前言 在上一周的学习中,我们熟悉了如何通过redux去管理数据,而在这一节中,我们将一起深入到redux的知识中学习. 首先谈一谈为什么要用到middleware 我们知道在一个简单的数据流场景中 ... 
- Eclipse项目红色叹号解决方法
			情况:就是项目出现红色感叹号 解决方法: 对准项目右键选择Build Path → configure build path 点击eclipse项目的configure build path后,在弹出 ... 
- vue实现对数据的增删改查(CURD)
			vue实现对数据的增删改查(CURD) 导语: 网上看到一个写的比较好的学习文章,转载分享一下 在管理员的一些后台页面里,个人中心里的数据列表里,都会有对这些数据进行增删改查的操作.比如在管理员后台的 ... 
- UVALive 6907 Body Building
			题目链接:https://vjudge.net/problem/UVALive-6907 题意: 给出一张图,判断这张图中有多少个哑铃,哑铃判断的条件是,对于一个连通图:如果找到一条边连接这两个点的个 ... 
- NOIP 2018 提高组初赛解题报告
			单项选择题: D 进制转换题,送分: D 计算机常识题,Python是解释运行的: B 常识题,1984年小平爷爷曰:“娃娃抓起”: A 数据结构常识题,带进去两个数据就可以选出来: D 历年真题没有 ... 
- 2018 计算之道初赛第二场 阿里巴巴的手机代理商(困难)(反向可持久化Trie)
			阿里巴巴的手机代理商(困难) 阿里巴巴的手机代理商正在研究 infra 输入法的新功能.他们需要分析单词频率以改进用户输入法的体验.于是需要你在系统内核里面写一个 API. API 有如下功能: 添加 ... 
- 50.分治算法练习:  二分算法:  2703 奶牛代理商 XII
			时间限制: 1 s 空间限制: 32000 KB 题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Description 小徐从美国回来后,成为了USACO中国区的奶牛销售代理商,专门出售 ... 
- MS SQL语句优化
			MS SQL Server查询优化方法查询速度慢的原因很多,常见如下几种 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计 ... 
- [转]android.support.v4.app.Fragment和android.app.Fragment区别
			1.最低支持版本不同 android.app.Fragment 兼容的最低版本是android:minSdkVersion="11" 即3.0版 android.support ... 
