老规矩,先上图:
image这个效果其实就是在上篇的HorizontalLayoutmanager的基础上进行修改
1、可以看到条目的起始位置是从屏幕的一半的地方再减去item宽度的一半的位置开始,而且每个item都是叠在上一个item宽度一般的位置
mStartX = getWidth()/2 - getItemShowWidth(); for (int i = 0; i < getItemCount(); i++) { Rect rect = new Rect(mStartX + temp, 0, mStartX + temp + mItemWidth, itemHeight); mSparseArray.put(i, rect); mBooleanArray.put(i, false); temp += getItemShowWidth(); } private int getItemShowWidth() { return mItemWidth / 2;}
image
2、我们可以看到所有的item都重叠起来了,画廊的效果是中间的item完全显示,而其它地方都只显示了一半,这里我们要重写Recycleview中的方法,来改变item绘制的顺序,我们想要画廊的效果是中间显示其它显示一半,所以我们中间的item最后来绘制,这里介绍下Recycleview中的这个方法
@Override protected int getChildDrawingOrder(int childCount, int i) { if (mChildDrawingOrderCallback == null) { return super.getChildDrawingOrder(childCount, i); } else { return mChildDrawingOrderCallback.onGetChildDrawingOrder(childCount, i); } }
childCount表示屏幕中可见的item个数,i表示要绘制的条目位置,i越小越先绘制,如下所示:
image前三个条目的位置和索引一样不用变,中间的为childCount-1,倒数第二个的绘图顺序是center,倒数第二个的绘图顺序是center+1,倒数第三个的绘图顺序是center+2,所以后三个对应的为center + childCount- 1 - i
public class GalleryRecycleview extends RecyclerView { public GalleryRecycleview(Context context) { this(context,null); } public GalleryRecycleview(Context context, @Nullable AttributeSet attrs) { super(context, attrs); setChildrenDrawingOrderEnabled(true); } @Override protected int getChildDrawingOrder(int childCount, int i) { int center = getlayoutManager().getCenterPos() - getlayoutManager().getFistvisiblePos(); //计算正在显示的所有Item的中间位置 int order; if (i == center) { order = childCount - 1; } else if (i > center) { order = center + childCount - 1 - i; } else { order = i; } return order; }
在layoutmanager中获取第一个可见item和中间item的位置
public int getCenterPos() { int pos = (mTotalMoveX / getItemShowWidth()); int more = (mTotalMoveX % getItemShowWidth()); if (more > getItemShowWidth() * 0.5f) pos++; return pos; } public int getFistvisiblePos() { if(getItemCount()==0){ return 0; } return getPosition(getChildAt(0)); }
image
可以看到已经是最后才绘制中间的item了
3、接着我们在layoutChild的时候加上动画
private void handleChildView(View child, int moveX) { float radio = computeScale(moveX); float rotation = computeRotationY(moveX); child.setScaleX(radio); child.setScaleY(radio); child.setRotationY(rotation); } private float computeScale(int x) { float scale = 1 - Math.abs(x * 1.0f / (6f * getItemShowWidth())); if (scale < 0) scale = 0; if (scale > 1) scale = 1; return scale; } /** * 最大Y轴旋转度数 */ private float M_MAX_ROTATION_Y = 30.0f; private float computeRotationY(int x) { float rotationY; rotationY = -M_MAX_ROTATION_Y * x / getItemShowWidth(); if (Math.abs(rotationY) > M_MAX_ROTATION_Y) { if (rotationY > 0) { rotationY = M_MAX_ROTATION_Y; } else { rotationY = -M_MAX_ROTATION_Y; } } return rotationY; }
就和最上面的效果一样了
源码地址:
https://github.com/digtal/recycleview-study
【附】相关架构及资料
image资料领取:
关注+点赞+加群:185873940 免费获取!
领取获取往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术
网友评论