gpt4 book ai didi

android - RecyclerView - 每次都滚动到不工作的位置

转载 作者:IT老高 更新时间:2023-10-28 22:19:43 56 4
gpt4 key购买 nike

我已经实现了一个水平滚动的RecyclerView。我的 RecyclerView 使用 LinearLayoutManager,我面临的问题是当我尝试使用 scrollToPosition(position)smoothScrollToPosition( position) 或来自 LinearLayoutManagerscrollToPositionWithOffset(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() 是因为 this但情况可能有所不同,因为我使用的是 LinearLayoutManager 而不是 GridLayoutManager。但该解决方案也适用于我,但正如我之前所说的,只是部分。

  • 当调用滚动是从第 0 个位置到 totalSize - 7 滚动就像一个魅力。
  • 当滚动从 totalSize - 7 到 totalSize - 3 时,我第一次只滚动到列表中的最后一项。但是第二次我可以很好地滚动
  • 从 totalSize - 3 滚动到 totalSize 时,我开始出现意外行为。

如果有人找到了解决方法,我会很感激。这是gist到我的自定义 ReyclerView 代码。

最佳答案

几周前我遇到了同样的问题,但发现只有一个非常糟糕的解决方案来解决它。必须使用 200-300 毫秒的 postDelayed

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
yourList.scrollToPosition(position);
}
}, 200);

如果您找到更好的解决方案,请告诉我!祝你好运!

关于android - RecyclerView - 每次都滚动到不工作的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426129/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com