我已经实现了一个横向滚动的RecyclerView
。我的RecyclerView
使用LinearLayoutManager
,我遇到的问题是,当我尝试使用scrollToPosition(position)
或smoothScrollToPosition(position)
或从LinearLayoutManager
的scrollToPositionWithOffset(position)
时,它们都不适用于我。要么滚动调用无法滚动到所需位置,要么它不会调用OnScrollListener
。
到目前为止,我尝试了很多不同的代码组合,无法在这里全部张贴。以下是对我有用(但仅部分)的代码:
public void smoothUserScrollTo(final int position) {
if (position < 0 || position > getAdapter().getItemCount()) {
Log.e(TAG, "An attempt to scroll out of adapter size has been stopped.");
return;
}
if (getLayoutManager() == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager is not set. " +
"Call setLayoutManager with a non-null layout.");
return;
}
if (getChildAdapterPosition(getCenterView()) == position) {
return;
}
stopScroll();
scrollToPosition(position);
if (lastScrollPosition == position) {
addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (left == oldLeft && right == oldRight && top == oldTop && bottom == oldBottom) {
removeOnLayoutChangeListener(this);
updateViews();
// removing the following line causes a position - 3 effect.
scrollToView(getChildAt(0));
}
}
});
}
lastScrollPosition = position;
}
@Override
public void scrollToPosition(int position) {
if (position < 0 || position > getAdapter().getItemCount()) {
Log.e(TAG, "An attempt to scroll out of adapter size has been stopped.");
return;
}
if (getLayoutManager() == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager is not set. " +
"Call setLayoutManager with a non-null layout.");
return;
}
// stopScroll();
((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(position, 0);
// getLayoutManager().scrollToPosition(position);
}
由于这个情况,我选择了scrollToPositionWithOffset()
,但是由于我使用的是LinearLayoutManager而不是GridLayoutManager,所以情况可能不同。但是这个解决方案对我也有效,但是如我之前所说,只部分有效。
- 当从第0个位置到totalSize-7时进行滚动工作得很好。
- 当从totalSize-7滚动到totalSize-3时,第一次我只能滚动到列表中的倒数第七项。然而第二次我可以正常滚动。
- 当从totalSize-3滚动到totalSize时,我开始出现意外行为。
如果有人找到解决方法,我会很感激。这是我自定义的ReyclerView
代码的要点。
myRecycleView.post(() -> myRecycleView.smoothScrollToPosition(position))
,它能更顺畅地滚动至目标位置。 - Sp4Rx