1.attachToRecyclerView
SnapHelper使用入口:attachToRecyclerView(),代码如下:
public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
throws IllegalStateException {
if (mRecyclerView == recyclerView) {
return; // nothing to do
}
if (mRecyclerView != null) {
destroyCallbacks();
}
mRecyclerView = recyclerView;
if (mRecyclerView != null) {
setupCallbacks();
//初始化Scroll对象,用来计算fling的距离
mGravityScroller = new Scroller(mRecyclerView.getContext(),
new DecelerateInterpolator());
//滑动到目标位置
snapToTargetExistingView();
}
}
private void destroyCallbacks() {
mRecyclerView.removeOnScrollListener(mScrollListener);
mRecyclerView.setOnFlingListener(null);
}
private void setupCallbacks() throws IllegalStateException {
if (mRecyclerView.getOnFlingListener() != null) {
throw new IllegalStateException("An instance of OnFlingListener already set.");
}
mRecyclerView.addOnScrollListener(mScrollListener);
mRecyclerView.setOnFlingListener(this);
}
2、snapToTargetExistingView
寻找目标位置及将目标View划定到屏幕中间是由snapToTargetExistingView()函数来实现的,snapToTargetExistingView的代码如下:
void snapToTargetExistingView() {
if (mRecyclerView == null) {
return;
}
RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
if (layoutManager == null) {
return;
}
//fling前的当前View
View snapView = findSnapView(layoutManager