作者:翰茂文虹152 | 来源:互联网 | 2023-05-18 14:36
利用google的design包里的CoordinatorLayout和AppBarLayout即可快速便捷实现,先看一下实现的效果图,如下:在来贴一下实现这种效果的布局源码,如下:
利用google的design包里的CoordinatorLayout和AppBarLayout即可快速便捷实现,先看一下实现的效果图,如下:
在来贴一下实现这种效果的布局源码,如下:
实现要点如下:
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 screen
enterAlways
: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern
enterAlwaysCollapsed
: 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滑动冲突的解决