【问题标题】:How to find the position of current visible item in RecyclerView?如何在 RecyclerView 中找到当前可见项的位置?
【发布时间】:2019-05-21 13:18:39
【问题描述】:

我正在开发一个使用 RecyclerView 幻灯片显示图像的应用程序。我使用下面的代码水平滚动回收站视图。

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

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

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

问题是我想获取当前可见项目的位置

holder.getAdapterPosition()

但它不起作用。谁能告诉我怎么做?

【问题讨论】:

  • 你为什么不用ViewPager
  • 我知道,但我不能使用 ViewPager。

标签: android android-recyclerview


【解决方案1】:

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

【讨论】:

  • 我在Recyclerview的onScrollListener()中使用了这些,但是没有用。
  • 您在使用这些软件时遇到了什么问题? @TavinderSingh
  • @karandeepsingh 我在 onScrollListener 中使用相同,它不起作用的原因是因为当用户滚动到前几天,我将数据添加到我的数据源中,并且 notifyItemInserted 运行。一旦运行,findFirstVisibleItemPosition 返回 0
【解决方案2】:

以下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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多