Android获取RecyclerView中可见子项的计数

时间:2017-08-24 10:45:30

标签: android android-recyclerview

我想知道recyclerview中有多少项目对用户可见,在某些设备中,这个数量不同,我无法通过以下代码计算:

private int countVisibleRow() {
    if (messagesView.getLayoutManager() != null) {
       LinearLayoutManager layoutManager = (LinearLayoutManager) messagesView.getLayoutManager();
       int                 first         = layoutManager.findFirstVisibleItemPosition();
       int                 last          = layoutManager.findLastVisibleItemPosition();
       return last - first;
    } else {
       return 0;
    }
}

2 个答案:

答案 0 :(得分:0)

将你的代码放在onScroll listner方法中,只要你将滚动recylerView,这个方法就会被激活(将这段代码放在你的Adapter类的构造函数中)

final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        //Add this to your Recyclerview
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //To check if  recycler last Visible Item
                int lastVisiblePos = layoutManager.findLastCompletelyVisibleItemPosition();
                int  firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

                }
            }
        });

答案 1 :(得分:0)

尝试如下:

   layoutmanager = new LinearLayoutManagerWithSmoothScroller(QuestionsActivity.this);
  paginationRV.setLayoutManager(layoutmanager);

使用如下:

.zip