RecyclerView可见计数给出Recyclerview中的总项目

时间:2018-04-05 13:49:06

标签: android

我正在使用RecyclerView来显示项目列表。总项目是10,但一次可见是3.但是当我使用recyclerView.getChildCount()方法获得可见计数时,它给我10,而不是3.可能是什么问题。我正在尝试实现分页。因此,每当我的可见计数与totalitemcount相同时,我的负载就会被连续调用,直到所有页面都被加载。以下是我的代码。

 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    if (dy > 0) {
        onScrolled();
    }



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

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

        // Do something
        current_page++;

        onLoadMoreData(current_page);

        loading = true;
    }

}

2 个答案:

答案 0 :(得分:4)

检查此答案:Get visible items in RecyclerView

<小时/>  仅基于该答案,您可以执行以下操作:

LinearLayoutManager layoutManager = ((LinearLayoutManager)mRecyclerView.getLayoutManager());

int visibleItemCount = layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition();

希望它有所帮助。

答案 1 :(得分:0)

To get the number of items visible on the screen of the recycler view.

rvBreakingNews.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val mLayoutManger = recyclerView.layoutManager as LinearLayoutManager
                //To get the total Number of items visible on the screen
                val visibleItemCount = mLayoutManger.childCount 
              //To get the total items loaded in the RecyclerView
                val totalItemCount = mLayoutManger.itemCount 

        })