之前我在GitHub上开源了一个可以实现RecyclerView列表分组的通用Adapter:
为了给RecyclerView实现头部悬浮的功能,我在GroupedRecyclerViewAdapter框架里添加了一个StickyHeaderLayout控件,由StickyHeaderLayout实现头部悬浮效果并且管理悬浮吸顶的View。下面我会给出StickyHeaderLayout源码,我在源码中对StickyHeaderLayout的实现有了比较详细的注释,相信大家能很好的理解。由于StickyHeaderLayout是对GroupedRecyclerViewAdapter的功能拓展,它跟GroupedRecyclerViewAdapter密切相关。所以你在阅读它的源码前,需要先了解GroupedRecyclerViewAdapter,而且StickyHeaderLayout也是要与GroupedRecyclerViewAdapter一起使用的。要想了解GroupedRecyclerViewAdapter,请看我的另一篇文章:《Android 可分组的RecyclerViewAdapter
》。如果你只是想使用它的功能,而不需要了解它的实现原理,也可以直接访问我的GitHub。
StickyHeaderLayout的源码:
/**
* Depiction:头部吸顶布局。只要用StickyHeaderLayout包裹{@link RecyclerView},
* 并且使用{@link GroupedRecyclerViewAdapter},就可以实现列表头部吸顶功能。
* StickyHeaderLayout只能包裹RecyclerView,而且只能包裹一个RecyclerView。
*
* Author:donkingliang
* Dat:2017/11/14
*/
public class StickyHeaderLayout extends FrameLayout {
private Context mContext;
private RecyclerView mRecyclerView;
//吸顶容器,用于承载吸顶布局。
private FrameLayout mStickyLayout;
//保存吸顶布局的缓存池。它以列表组头的viewType为key,ViewHolder为value对吸顶布局进行保存和回收复用。
private final SparseArray mStickyViews = new SparseArray<>();
//用于在吸顶布局中保存viewType的key。
private final int VIEW_TAG_TYPE = -101;
//用于在吸顶布局中保存ViewHolder的key。
private final int VIEW_TAG_HOLDER = -102;
//记录当前吸顶的组。
private int mCurrentStickyGroup = -1;
//是否吸顶。
private boolean isSticky = true;
public StickyHeaderLayout(@NonNull Context context) {
super(context);
mContext = context;
}
public StickyHeaderLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public StickyHeaderLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr