项目要用到粘性头部,以前的ListView和GridView的还好整,RecycleView的一片茫然,在github上找了很多发现好复杂,使用ItemDecoration实现,这货以我的智商真难搞懂,或者只适配了LinearLayoutManager和GridLayoutManager,很少适配了StaggeredGridLayoutManager,我的需求恰恰是瀑布流,只设置两个粘性头部,于是我利用帧布局and监听滑动事件移动布局来实现了这一需求。
首先看下Demo的效果图吧:
是不是还过得去呢^_^,接下来贴代码,代码有详细的注释了
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:scrollbars="none" />
<RelativeLayout
android:id="@+id/rl_sticky_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2.5dp"
android:layout_marginRight="2.5dp">
<include layout="@layout/flashgo_header" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_sticky_head_fake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2.5dp"
android:layout_marginRight="2.5dp"
android:visibility="invisible">
<include
android:id="@+id/tv_fake_sticky_head"
layout="@layout/flashgo_header" />
</RelativeLayout>
</FrameLayout>
主布局为一个帧布局,包含了RecyclerView和两个flashgo_header,flashgo_header布局是用来做为粘性头部的,RecyclerView在位置0那里会相应地添加一个flashgo_header布局,这样子RecyclerView那么真正要展示的图片位置就不会收到遮掩了,
那么干哈要两个呢,rl_sticky_head是作为Header One使用的;rl_sticky_head_fake是作为Header Two使用的,最外层就是它了,默认为INVISIBLE。
它的使用如下图讲解所示,是用来伪造RecycleView头部二到顶部固定的效果
然后就是MainActivity的代码了:
该解释的都解释了……
public class MainActivity extends AppCompatActivity{
private int mHalfScreenWidth;
private RecyclerView mRecyclerView;
private RecyclerAdapter mAdapter;
private StaggeredGridLayoutManager mManager;
private RelativeLayout mStickyHeadLayout;
private RelativeLayout mFakeStickyHeadLayout;
private TextView mStickyHead;
private TextView mFakeStickyHead;
private int mStickyHeadHeight;
private int mHeaderOneCount &