2

我有一个项目清单。这些项目按日期排序。当用户打开应用程序时,日期之前的项目(“旧”项目)应该不可见,但用户应该能够通过滚动列表到顶部来查看它们。

我找到position了未来日期的第一个项目(“新”项目)并调用recyclerView.scrollToPosition(position).

我也试过了layoutManager.scrollToPositionWithOffset(position, 0)

如果列表中有许多“新”项目,则此方法有效。

但如果项目太少(例如,一个“旧”和一个“新”),则这些方法不起作用。

无论列表中有多少项目,如何以编程方式滚动列表到给定位置的项目以将此项目放在顶部?

4

1 回答 1

2

Initially, provide the RecyclerView with a dataset that has only the future events.

Set an onTouchListner on recyclerView to detect upward scroll. If findFirstCompletelyVisibleItemPosition() returns the first index when you detect an upward scroll, it means an upward overscroll. Then, change the data set to include the old entries. Then, use adapter.notifyDataSetChanged() to notify the adapter of the dataset change and list will be redrawn.

NOTE :

  1. When you set onTouchListner on the RecyclerView make sure you don't absorb the touch event [onTouchEvent() should return false].

  2. Once, you've detected an upward overscroll for the first time, you can set a flag to indicate that you don't need to change the dataset for future touch events.

于 2016-05-16T13:18:06.737 回答