RecyclerView滑动至指定position解决方案

RecyclerView滑动至指定position解决方案


	new LinearSmoothScroller(this) {
            @Override
            protected int getVerticalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }

     };
        

重写LinearSmoothScroller的getVerticalSnapPreference()方法,通过查看父类方法注释可知:

/**
* When scrolling towards a child view, this method defines whether we should align the top
* or the bottom edge of the child with the parent RecyclerView.
*
* @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY; depending on the current target vector
* @see #SNAP_TO_START
* @see #SNAP_TO_END
* @see #SNAP_TO_ANY
*/
protected int getVerticalSnapPreference() {
return mTargetVector == null || mTargetVector.y == 0 ? SNAP_TO_ANY :
mTargetVector.y > 0 ? SNAP_TO_END : SNAP_TO_START;
}

我们要想child view 的第一个条目Top与父View的Top齐平需要选用SNAP_TO_START模式。

使用方法:


 linearSmoothScroller.setTargetPosition(position);
 
 recyclerView.getLayoutManager().startSmoothScroll(linearSmoothScroller);
 

如需要改变滑动速度:


    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
        return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
    }
    

重写calculateSpeedPerPixel(DisplayMetrics displayMetrics)方法,displayMetrics值越大滑动速率越慢,反之越快。
注意不要设置太小,否则会出现意想不到的错误:

 if (mConsecutiveUpdates > 10) {
      // A new action is being set in every animation step. This looks like a bad
      // implementation. Inform developer.
      Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
              + " you are not changing it unless necessary");
   }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值