利用google的design包里的CoordinatorLayout和AppBarLayout即可快速便捷实现,先看一下实现的效果图,如下:
在来贴一下实现这种效果的布局源码,如下:
<?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"
app:elevation="0dp">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@android:color/holo_orange_light"
android:gravity="center"
android:text="这是头部滚动部分"
app:layout_scrollFlags="scroll"/>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@android:color/holo_blue_light"
android:gravity="center"
android:text="这是悬停部分"/>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0000"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
实现要点如下:
1) 首先需要用CoordinatorLayout包住AppBarLayout
2) 顶部可以滚动隐藏和悬停的部分都放在AppBarLayout里面
3) 与AppBarLayout平级的部分放一个带有可滚动的View,比如上面的例子RecyclerView
4) 在第2步中可以滚动隐藏的View里面加上app:layout_scrollFlags="scroll"
5) 在第3步添加的可滚动的View加上app:layout_behavior="@string/appbar_scrolling_view_behavior"
完成以上五个步骤,就请尽情享受design包带来的便利吧,很方便快捷地实现了滚动头部悬停效果。
参考资料:
app:layout_scrollFlags有4种类型:
scroll
: this flag should be set for all views that want to scroll off the screen - for views that do not use this flag, they’ll remain pinned to the top of the screenenterAlways
: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ patternenterAlwaysCollapsed
: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.exitUntilCollapsed
: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting
其他问题:
在实现的第3步当中,如果你用ListView就会发现并不能很好地实现效果,这是为什么呢?
在查阅了相关资料后,发现由于CoordinatorLayout实现NestedScrollingParent接口,RecycleView实现了NestedScrollingChild接口,所以就可以在NestedScrollingChildHelper的帮助下实现滑动联动,而ListView并没有实现NestedScrollingChild接口,所以解决方案有两种:
1)将ListView改为RecyclerView实现
2)自定义ListView实现NestedScrollingChild接口
方案2请参考关于CoordinatorLayout和ListView滑动冲突的解决