如何在RecyclerView中找到当前可见项目的位置?

时间:2018-02-08 14:36:04

标签: android android-recyclerview

我正在开发一款使用RecyclerView幻灯片显示图片的应用。我使用以下代码水平滚动回收器视图。

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
imageListRecyclerView.setLayoutManager(mLayoutManager);

另外,我使用以下代码一次滚动一个项目。

SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(imageListRecyclerView);

问题是我想使用

获取当前可见项目的位置
holder.getAdapterPosition()

但它不起作用。谁能说出怎么做呢?

2 个答案:

答案 0 :(得分:3)

LinearLayoutManager

有一些辅助方法
findFirstCompletelyVisibleItemPosition()
Returns the adapter position of the first fully visible view.

int findFirstVisibleItemPosition()
Returns the adapter position of the first visible view.

int findLastCompletelyVisibleItemPosition()
Returns the adapter position of the last fully visible view.

findLastVisibleItemPosition()

有关详情,请查看this official document

答案 1 :(得分:0)

可以使用以下Linear / Grid LayoutManager方法来检查哪些项目是visible

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

int findFirstVisibleItemPosition();
int findLastVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

如果您要跟踪is item visible on screen的某些threshold的意思是user spent enough time to view the content,则可以参考以下博客。

一个非常不错的博客,该博客演示了如何使用scroll callbacks of LayoutManagerRxJava Subscribers来跟踪项目可见性是否达到阈值 https://proandroiddev.com/detecting-list-items-perceived-by-user-8f164dfb1d05

相关问题