源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android中RecyclerView实现分页滚动的方法详解

  • 时间:2022-06-02 20:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android中RecyclerView实现分页滚动的方法详解
[b]一、需求分析[/b] [b]最近公司项目要实现一个需求要满足以下功能:[/b]       1)显示一个 list 列表, item 数量不固定。       2)实现翻页功能,一次翻一页。       3)实现翻至某一页功能。 [b]下面介绍通过 RecyclerView 实现该需求的实现过程(效果图如下)。[/b] [img]http://files.jb51.net/file_images/article/201704/2017424152124764.gif?2017324152134[/img] [b]二、功能实现[/b] [b]2.1 OnTouchListener 记录当前开始滑动位置[/b] 要实现翻页滑动首先我们要确定是向前翻页还是向后翻页,这里通过记录开始翻页前当前的位置和滑动后的位置比较即可得知,下面选择手指触摸按下时滑动的位置为当前开始滑动位置:
 //当前滑动距离
 private int offsetY = 0;
 private int offsetX = 0;
 //按下屏幕点
 private int startY = 0;
 private int startX = 0;
@Override
  public boolean onTouch(View v, MotionEvent event) {
   //手指按下的时候记录开始滚动的坐标
   if (event.getAction() == MotionEvent.ACTION_DOWN) {
    //手指按下的开始坐标
    startY = offsetY;
    startX = offsetX;
   }
   return false;
  }
 }
好了,当我们确定了滑动方向,下面要考虑的就是如何实现滑动? [b]2.2 scrollTo(int x, int y) 和 scrollBy(int x, int y) 实现滑动[/b] 滑动我们最容易想到的方法就是 [code]scrollTo(int x, int y)[/code] 和 [code]scrollBy(int x, int y) [/code]这两个方法, [code]scrollTo(int x, int y) [/code]是将当前 View 的内容滑动至某一位置, [code]scrollBy(int x, int y)[/code] 是将当前 View 内容相对于当前位置滑动一定的距离,其实 [code]scrollBy(int x, int y) [/code]内部是调用了 [code]scrollTo(int x, int y)[/code] 方法实现的 一开始想用 [code]scrollTo(int x, int y)[/code] 去实现,但是简单看了下源码发现, RecyclerView 不支持这个方法:
@Override
 public void scrollTo(int x, int y) {
  Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. "
    + "Use scrollToPosition instead");
 }
所以这里我们就选择使用 [code]scrollBy(int x, int y) [/code]去实现滑动。 [b]2.3 OnFlingListener 和 OnScrollListener 调用滑动时机[/b] 上面我们决定使用 [code]scrollBy(int x, int y) [/code]去实现滑动,那么现在我们就要确定 [code]scrollBy(int x, int y) [/code]这个方法的调用时机,我们知道当我们滑动 RecyclerView 的时候一般分为两种情况,一种是手指在屏幕上面缓慢滑动(Scroll),另一种是飞速滑动(onFling),经过一番查阅,发现 RecyclerView 中有这两种状态的监听,那么我们一起看一下这两种状态的方法定义,先看 [code]onFling(int velocityX, int velocityY) [/code]: Note: 由于使用了 RecyclerView 的 OnFlingListener,所以 RecycleView 的版本必须要 recyclerview-v7:25.0.0 以上。
/**
 * This class defines the behavior of fling if the developer wishes to handle it.
 * <p>
 * Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior.
 *
 * @see #setOnFlingListener(OnFlingListener)
 */
 public static abstract class OnFlingListener {
  /**
  * Override this to handle a fling given the velocities in both x and y directions.
  * Note that this method will only be called if the associated {@link LayoutManager}
  * supports scrolling and the fling is not handled by nested scrolls first.
  *
  * @param velocityX the fling velocity on the X axis
  * @param velocityY the fling velocity on the Y axis
  *
  * @return true if the fling washandled, false otherwise.
  */
  public abstract boolean onFling(int velocityX, int velocityY);
 }
方法的注释写的也很清楚,当这个方法被调用并且返回 true 的时候系统就不处理滑动了,而是将滑动交给我们自己处理。所以我们可以监听这个方法,当我们执行快速滑动的时候在这个方法里面计算要滑动的距离并执行 [code]scrollBy(int x, int y)[/code] 实现滑动,然后直接返回 true,表示滑动我们自己处理了,不需要系统处理。 处理代码如下:
 //当前滑动距离
 private int offsetY = 0;
 private int offsetX = 0;
 //按下屏幕点
 private int startY = 0;
 private int startX = 0;
 //最后一个可见 view 位置
 private int lastItemPosition = -1;
 //第一个可见view的位置
 private int firstItemPosition = -2;
 //总 itemView 数量
 private int totalNum;
@Override
  public boolean onFling(int velocityX, int velocityY) {
   if (mOrientation == ORIENTATION.NULL) {
    return false;
   }
   //获取开始滚动时所在页面的index
   int page = getStartPageIndex();
   //记录滚动开始和结束的位置
   int endPoint = 0;
   int startPoint = 0;
   //如果是垂直方向
   if (mOrientation == ORIENTATION.VERTICAL) {
    //开始滚动位置,当前开始执行 scrollBy 位置
    startPoint = offsetY;
    if (velocityY < 0) {
     page--;
    } else if (velocityY > 0) {
     page++;
    } else if (pageNum != -1) {
     if (lastItemPosition + 1 == totalNum) {
      mRecyclerView.scrollToPosition(0);
     }
     page = pageNum - 1;
    }
    //更具不同的速度判断需要滚动的方向
    //一次滚动一个 mRecyclerView 高度
    endPoint = page * mRecyclerView.getHeight();
   } else {
    startPoint = offsetX;
    if (velocityX < 0) {
     page--;
    } else if (velocityX > 0) {
     page++;
    } else if (pageNum != -1) {
     if (lastItemPosition + 1 == totalNum) {
      mRecyclerView.scrollToPosition(0);
     }
     page = pageNum - 1;
    }
    endPoint = page * mRecyclerView.getWidth();
   }
   //使用动画处理滚动
   if (mAnimator == null) {
    mAnimator = ValueAnimator.ofInt(startPoint, endPoint);
    mAnimator.setDuration(300);
    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
     @Override
     public void onAnimationUpdate(ValueAnimator animation) {
      int nowPoint = (int) animation.getAnimatedValue();
      if (mOrientation == ORIENTATION.VERTICAL) {
       int dy = nowPoint - offsetY;
       if (dy == 0) return;
       //这里通过RecyclerView的scrollBy方法实现滚动。
       mRecyclerView.scrollBy(0, dy);
      } else {
       int dx = nowPoint - offsetX;
       mRecyclerView.scrollBy(dx, 0);
      }
     }
    });
    mAnimator.addListener(new AnimatorListenerAdapter() {
     //动画结束
     @Override
     public void onAnimationEnd(Animator animation) {
      //回调监听
      if (null != mOnPageChangeListener) {
       mOnPageChangeListener.onPageChange(getPageIndex());
      }
      //滚动完成,进行判断是否滚到头了或者滚到尾部了
      RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
      //判断是当前layoutManager是否为LinearLayoutManager
      // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
      if (layoutManager instanceof LinearLayoutManager) {
       LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
       //获取最后一个可见view的位置
       lastItemPosition = linearManager.findLastVisibleItemPosition();
       //获取第一个可见view的位置
       firstItemPosition = linearManager.findFirstVisibleItemPosition();
      }
      totalNum = mRecyclerView.getAdapter().getItemCount();
      if (totalNum == lastItemPosition + 1) {
       updateLayoutManger();
      }
      if (firstItemPosition == 0) {
       updateLayoutManger();
      }
     }
    });
   } else {
    mAnimator.cancel();
    mAnimator.setIntValues(startPoint, endPoint);
   }
   mAnimator.start();
   return true;
  }
 }
再看 OnScrollListener 滚动监听方法:
public abstract static class OnScrollListener {
  /**
  * Callback method to be invoked when RecyclerView's scroll state changes.
  *
  * @param recyclerView The RecyclerView whose scroll state has changed.
  * @param newState  The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
  *      {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
  */
  public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
  /**
  * Callback method to be invoked when the RecyclerView has been scrolled. This will be
  * called after the scroll has completed.
  * <p>
  * This callback will also be called if visible item range changes after a layout
  * calculation. In that case, dx and dy will be 0.
  * 滚动完成调用
  * @param recyclerView The RecyclerView which scrolled.
  * @param dx The amount of horizontal scroll.
  * @param dy The amount of vertical scroll.
  */
  public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
 }
这个监听类主要有两个方法一个是 [code]onScrollStateChanged(RecyclerView recyclerView, int newState) [/code]滚动状态发生变化调用, [code]onScrolled(RecyclerView recyclerView, int dx, int dy) RecyclerView [/code]发生滚动和滚动完成调用。有了这两个监听,当我们进行缓慢滑动我们就可以在 [code]onScrollStateChanged(RecyclerView recyclerView, int newState) [/code]中监听滑动如果结束并且超过一定距离去执行翻页,而通过 [code]onScrolled(RecyclerView recyclerView, int dx, int dy) [/code]方法可以记录当前的滑动距离。 处理方法如下:
@Override
  public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
   //如果滑动停止
   if (newState == RecyclerView.SCROLL_STATE_IDLE && mOrientation != ORIENTATION.NULL) {
    boolean move;
    int vX = 0, vY = 0;
    if (mOrientation == ORIENTATION.VERTICAL) {
     int absY = Math.abs(offsetY - startY);
     //如果滑动的距离超过屏幕的一半表示需要滑动到下一页
     move = absY > recyclerView.getHeight() / 2;
     vY = 0;
     if (move) {
      vY = offsetY - startY < 0 ? -1000 : 1000;
     }
    } else {
     int absX = Math.abs(offsetX - startX);
     move = absX > recyclerView.getWidth() / 2;
     if (move) {
      vX = offsetX - startX < 0 ? -1000 : 1000;
     }
    }
    //调用滑动
    mOnFlingListener.onFling(vX, vY);
   }
  }
 @Override
  public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
   //滚动结束记录滚动的偏移量
   //记录当前滚动到的位置
   offsetY += dy;
   offsetX += dx;
  }
 }
到这里我们要实现滑动的方法和时机基本就搞定了,剩下的就是滑动位置计算和滑动效果实现,滑动位置计算就是一次滑动一整页,这个没什么可说的,所以简单说下实现弹性滑动效果。 [b]2.4 ValueAnimator 实现弹性滑动效果[/b] 我们知道如果我们直接调用[code] scrollBy(int x, int y)[/code] 这个方法去滑动,那么是没有缓慢滑动的效果,看着有点愣,所以这里我们通过 ValueAnimator 这个类来实现缓慢滑动的效果,这个就很简单了,直接贴代码:
if (mAnimator == null) {
    mAnimator = ValueAnimator.ofInt(startPoint, endPoint);
    mAnimator.setDuration(300);
    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
     @Override
     public void onAnimationUpdate(ValueAnimator animation) {
      int nowPoint = (int) animation.getAnimatedValue();
      if (mOrientation == ORIENTATION.VERTICAL) {
       int dy = nowPoint - offsetY;
       if (dy == 0) return;
       //这里通过RecyclerView的scrollBy方法实现滚动。
       mRecyclerView.scrollBy(0, dy);
      } else {
       int dx = nowPoint - offsetX;
       mRecyclerView.scrollBy(dx, 0);
      }
     }
    });
[b]2.5 翻页至某一页[/b] 这里翻页至某一页的实现有了上面的基础就很好实现了,就是直接调用 我们已经实现好了的 [code]onFling(int velocityX, int velocityY) [/code]方法,然后把页数传递过去计算一下就可以了 :
public void setPageNum(int page) {
 this.pageNum = page;
 mOnFlingListener.onFling(0, 0);
}
到这里前面说的功能已经全部实现完毕. 具体代码细节请见: github 地址: [url=https://github.com/yongyu0102/PageRecyclerView]pagerecyclerview[/url] 本地下载:[url=http://xiazai.jb51.net/201704/yuanma/PageRecyclerView-master(jb51.net).rar]点击这里[/url] [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对各位Android开发者们能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部