RecyclerView滑动指定item到屏幕最顶部
2019-04-18 本文已影响0人
灰色轨迹_e2d8
一开始调用RecyclerView提供的方法
public void smoothScrollToPosition(int position) {
if (mLayoutFrozen) {
return;
}
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}
发现当指定item滑动到屏幕可见时就停止了,即item可能位于屏幕顶部、中部或者底部。
由代码可以看出,RecyclerView的滑动方法是调用LayoutManager的smoothScrollToPosition方法
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext());
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
其中LinearSmoothScroller提供了滑动策略
public static final int SNAP_TO_START = -1;
/**
* Align child view's right or bottom with parent view's right or bottom
*
* @see #calculateDtToFit(int, int, int, int, int)
* @see #calculateDxToMakeVisible(android.view.View, int)
* @see #calculateDyToMakeVisible(android.view.View, int)
*/
public static final int SNAP_TO_END = 1;
/**
* <p>Decides if the child should be snapped from start or end, depending on where it
* currently is in relation to its parent.</p>
* <p>For instance, if the view is virtually on the left of RecyclerView, using
* {@code SNAP_TO_ANY} is the same as using {@code SNAP_TO_START}</p>
*
* @see #calculateDtToFit(int, int, int, int, int)
* @see #calculateDxToMakeVisible(android.view.View, int)
* @see #calculateDyToMakeVisible(android.view.View, int)
*/
public static final int SNAP_TO_ANY = 0;
重写LinearSmoothScroller的getVerticalSnapPreference方法
class LinearTopSmoothScroller extends LinearSmoothScroller{
public LinearTopSmoothScroller(Context context) {
super(context);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
然后滑动的代码可以这样写
void scrollItemToTop(int position){
LinearSmoothScroller smoothScroller = new LinearTopSmoothScroller(this);
smoothScroller.setTargetPosition(position);
linearLayoutManager.startSmoothScroll(smoothScroller);
}
完美解决。