Post

Android's RecyclerView(2) 视差滚动

RecyclerView的视差滚动
parallaxrecycler 实现的这个需求的话,需要知道当前滚动的距离,这里可以通过设置监听setOnScrollListener的方式获取,这样就有视差滚动的视差效果了,但是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
RecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (mHeader != null) {
        	RecyclerView.ViewHolder holder = RecyclerView.findViewHolderForPosition(0);
        	if (holder != null) {
            	int startTop = holder.itemView.getTop();
        		float ofCalculated = startTop * SCROLL_MULTIPLIER;
       		 	ViewCompat.setTranslationY(mHeader, -ofCalculated);
            	...
        	}
        }
    }
});

因为这个View虽然移动的,占据的位置没有变化,我们应该切掉这部分多余的,于是对于header 部分剪掉多余的

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
protected void dispatchDraw(Canvas canvas) {
    Log.i("dispatchDraw", "mOffset=" + mOffset + " ;getLeft()=" + getLeft()
            + " ;getRight()=" + getRight() + " ;getTop()=" + getTop() + " ;getBottom()="
            + getBottom());
    canvas.clipRect(new Rect(getLeft(), getTop(), getRight(), getBottom() + mOffset));
    super.dispatchDraw(canvas);
}

public void setClipY(int offset) {
    mOffset = offset;
    invalidate();
}

当前的滚动的进度就是startTop/mHeader.getHeight().

源码地址
AndroidRecyclerViewDemo 参考
android-parallax-recyclerview

This post is licensed under CC BY 4.0 by the author.