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

前端之家收集整理的这篇文章主要介绍了android – RecyclerView Infinite Scroll监听器被调用两次前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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)同样

原文链接:https://www.f2er.com/android/309902.html

猜你在找的Android相关文章