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");
}