我想确定RecyclerView中最明显的项目,因此我使用以下方法:
public int getMostVisibleIndex() {
// try to figure which child is the most visible on screen
LinearLayoutManager layoutManager = ((LinearLayoutManager) getLayoutManager());
mFirstVisibleIndex = layoutManager.findFirstVisibleItemPosition();
mLastVisibleIndex = layoutManager.findLastVisibleItemPosition();
// How do I use convertPreLayoutPositionToPostLayout() ?
VisibleIndex mostVisible = null;
if (mFirstVisibleIndex != -1|| mLastVisibleIndex != -1) {
// if it's not the same
if (mFirstVisibleIndex != mLastVisibleIndex) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) this.getLayoutManager();
// get the visible rect of the first item
Rect firstPercentageRect = new Rect();
linearLayoutManager.findViewByPosition(mFirstVisibleIndex).getGlobalVisibleRect(firstPercentageRect);
// get the visible rect of the last item
Rect lastPercentageRect = new Rect();
linearLayoutManager.findViewByPosition(mLastVisibleIndex).getGlobalVisibleRect(lastPercentageRect);
// since we're on a horizontal list
if (firstPercentageRect.width() > lastPercentageRect.width()) {
return mFirstVisibleIndex;
} else {
return mLastVisibleIndex;
}
} else {
return mFirstVisibleIndex;
}
}
return -1;
}
它工作得很好,但在我更改数据集并调用我的适配器中的任何notify*Changed
方法后,如果我尝试使用上述函数,则项目将findFirstVisibleItemPosition
和{{1返回错误。
我注意到他们都在幕后使用getlayoutposition,我也注意到它在文档上说:
如果LayoutManager需要调用需要项的适配器位置的外部方法,则可以使用getAdapterPosition()或convertPreLayoutPositionToPostLayout(int)。
听起来好像findLastVisibleItemPosition
完全是我正在寻找的,但我不知道如何从convertPreLayoutPositionToPostLayout
内访问它。
有什么想法吗?
谢谢。
答案 0 :(得分:1)
在我的情况下,一次在recyclerview中我最多只能有2个可见视图,并且
我一直在onScrolled
中使用mostVisibleItemPosition
中的此方法
用户滚动时播放视频内容。
因此,getTop()
返回此视图相对于其父视图的顶部位置,并且当用户开始滚动时firstView
离开屏幕,而firstView.getTop()
将返回负值,而{{1 }}为正数,当secondView.getTop()
top到达屏幕中心附近时,获得secondView
的绝对值,我们将确定父视图top上方firstView.getTop()
top的像素数并获得{{ 1}},我们将确定firstView
顶部在父底部上方有多少像素,这就是secondView.getTop()
会发生变化的地方。
secondView