我想检查
smoothScrollToPosition
何时完成滚动回 recyclerview
的第一项。我尝试这样做,只有当 smoothScrollToPosition 仍在滚动时才有效:
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), 0);
if (!recyclerView.getLayoutManager().isSmoothScrolling()) {
Log.d(TAG, "Scrolling has ended.");
}
我使用
onScrollStateChanged(RecyclerView recyclerView, int newState)
方法来跟踪滚动状态。启动滚动的方法如下所示:
private void scrollToPosition(int position){
recyclerView.removeOnScrollListener(onScrollListener);
recyclerView.addOnScrollListener(onScrollListener);
recyclerView.smoothScrollToPosition(position);
}
这是听众:
RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case SCROLL_STATE_IDLE:
//we reached the target position
recyclerView.removeOnScrollListener(this);
break;
}
}
};
所以,当recyclerView达到SCROLL_STATE_IDLE时,就意味着它已经完成滚动。不要忘记在这种状态下删除侦听器,这样它就不会在下一次滚动时触发。
您可以自定义
LinearLayoutManager
来实现onStop
回调
public class XLinearLayoutManager extends LinearLayoutManager {
private OnLayoutManagerListener mListener;
public interface OnLayoutManagerListener {
void onSmoothScrollStopped();
}
public XLinearLayoutManager(Context context) {
super(context);
}
public void setLayoutManagerListener(OnLayoutManagerListener listener) {
mListener = listener;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
// super.smoothScrollToPosition(recyclerView, state, position);
// clone super.smoothScrollToPosition and add onStop callback
final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
@Override
protected void onStop() {
super.onStop();
if (mListener != null) {
mListener.onSmoothScrollStopped();
}
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
}
并在调用平滑滚动之前实现监听器
// setup LayoutManager for RecyclerView
final XLinearLayoutManager layoutManager = new XLinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
// call smoothScrollToPosition
layoutManager.setLayoutManagerListener(new OnLayoutManagerListener() {
@Override
public void onSmoothScrollStopped() {
//TODO: smoothScrollToPosition finished
}
});
recyclerView.smoothScrollToPosition(position);
有一个监听器:
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.OnScrollListener
void onScrolled (RecyclerView recyclerView,
int dx,
int dy)
RecyclerView 滚动时调用的回调方法。 滚动完成后将调用此函数。