2

I have a list of items. These items are sorted by date. Items with date before now ("old" items) should not be visible when user opens application but user should be able to see them by scrolling list to top.

I find position of first item with date in the future ("new" item) and call recyclerView.scrollToPosition(position).

I also tried layoutManager.scrollToPositionWithOffset(position, 0).

This works if there are many "new" items in the list.

But if there are too few items (for example, one "old" and one "new") then these methods do not work.

How can I scroll list programmatically to item at given position to place this item on top regardless of how many there are items in the list?

mixel
  • 25,177
  • 13
  • 126
  • 165
  • try this adapter.notifydatasetchanged(); before calling recyclerView.scrollToPosition(position); – IMRAN May 16 '16 at 11:53
  • `adapter` is already initialized with items and bound to `recyclerView` when I call `recyclerView.scrollToPosition()`. Also `adapter.notifyDataSetChanged()` is called before that. – mixel May 16 '16 at 11:56

1 Answers1

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.

cchapman
  • 3,269
  • 10
  • 50
  • 68
Karthiksrndrn
  • 188
  • 1
  • 12