使用协调者布局(CoordinatorLayout),可以在recyclerView中添加头部,或者在ViewPager等复杂的页面中使滚动的部分与其他区域协调滚动,从而达到一起滚动的效果.
要做到这种效果以上三个空间是必须使用到的而且必须是包裹关系,即从外到内:
CoordinatorLayout->你要使用的控件A和AppBarLayout->CollapsingToolbarLayout->你要显示的头部布局B
注意,以上A必须是滚动的控件,listView、recyclerView….(可使用以下属性保持头部在可滚动的布局的上方)
app:layout_behavior="@string/appbar_scrolling_view_behavior"
1.在AppBarLayout中的控件需要使用app:layout_scrollFlags属性控制布局跟滚动时的出现关系(可以多个属性连用用 | 隔开):
- scroll:值设为scroll的View会跟随滚动事件一起发生移动。
- enterAlways:值设为enterAlways的View,当ScrollView往下滚动时,该View会直接往下滚动。而不用考虑ScrollView是否在滚动。
- exitUntilCollapsed:值设为exitUntilCollapsed的View,当这个View要往上逐渐“消逝”时,会一直往上滑动,直到剩下的的高度达到它的最小高度后,再响应ScrollView的内部滑动事件。
- enterAlwaysCollapsed:是enterAlways的附加选项,一般跟enterAlways一起使用,它是指,View在往下“出现”的时候,首先是enterAlways效果,当View的高度达到最小高度时,View就暂时不去往下滚动,直到ScrollView滑动到顶部不再滑动时,View再继续往下滑动,直到滑到View的顶部结束。
2.在CollapsingToolbarLayout中的控件需要设置layout_collapseMode 来选择头部隐藏和显示时对应的状态
- parallax 滚动隐藏
- pin保持显示
- none 无动作
献上demoxml文件(之所以我用的viewpager 是因为在里面内容用了fragment+recyclerView的形式)
<?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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/sd_head"
android:layout_width="match_parent"
android:layout_height="200dp" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
android:background="@android:color/black"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
还有一些其他细节 以后再补充