我已经实现了水平滚动RecyclerView
。我RecyclerView
使用 a LinearLayoutManager
,我面临的问题是当我尝试使用scrollToPosition(position)
orsmoothScrollToPosition(position)
或 from时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
。