一、实现的效果
1、滑动的时候让每一个Item保持在中间
2、点击某一个Item让其滚动到中间
3、实际实现的效果如下:点击一次自动滚动居中,再次点击跳转到详情页
二、实现的思路:
1、每一次的滑动都让图片保持在中间,其实RecyclerView24.2.0版本以后,Google已经提供一个SnapHelper的辅助类,可以实现每一次滚动结束保持居中。具体用法就是:
LinearSnapHelper类似SnapHelper的一个子类,SnapHelper的另一个子类叫PagerSnapHelper。两者的作用都是滑动结束的时候Item保持在中间的位置。而区别是:LinearSnapHelper可以一次滑动多个Item,而PagerSnapHelper限制你一次只能滑动一个Item。
2、有了SnapHelper工具类解决Item居中问题,但是还需要考虑到一个问题,如何让刚开始的第一张和最后一张也居中呢?我们肯定会想到给第一张要显示的图片设置一个margin,这样第一张和最后一场也能也能居中显示。我们第一反应是在Adapter里直接修改item的LayoutParams,其实官方提供了ItemDecoration,就是给RecyclerView的Item添加修饰。代码如下:
public class GalleryItemDecoration extends RecyclerView.ItemDecoration {
/**
* 自定义默认的Item的边距
*/
private int mPageMargin = 10;
/**
* 第一张图片的左边距
*/
private int mLeftPageVisibleWidth;
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//计算一下第一中图片距离屏幕左边的距离:(屏幕的宽度-item的宽度)/2。其中item的宽度=实际ImagView的宽度+margin。
//我这里设置的ImageView的宽度为100+margin=110
if (mLeftPageV