gpt4 book ai didi

android - RecyclerView Infinite Scroll 监听器被调用两次

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:09 24 4
gpt4 key购买 nike

我有一个 RecyclerView,我试图在其中实现无限滚动功能。问题是,OnScrolled 方法中 if 语句中的代码被执行了两次。这是我当前的代码:

public abstract class InfiniteScroll extends RecyclerView.OnScrollListener {

private LinearLayoutManager mLayoutManager;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 1;

public InfiniteScroll(LinearLayoutManager layoutManager) {
mLayoutManager = layoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached

// Do something
current_page++;
Log.d("moreitems", "why is this being called twice?");
loadMore(current_page);

loading = true;
}
}

public abstract void loadMore(int current_page);
}

这段代码是作为对一个单独的 SO 问题的回答而发布的,其他示例的功能似乎相似,但我仍然在到达 底部时执行了两次 loadMore() 方法>RecyclerView,我不确定为什么。

最佳答案

它被调用是因为当您加载更多项目时,onScrolled 会再次被调用。

This callback will also be called if visible item range changes after a layout calculation. In that case, dx and dy will be 0.

所以你可以检查if (!loading && dy>0)还有

关于android - RecyclerView Infinite Scroll 监听器被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285574/

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