3

I have a callback that is fired after a programmatic scroll to a certain item of a RecyclerView via LinearLayoutManager.smoothScrollToPosition(). The user taps on an item and the right item is scrolled to the top of the RecyclerView. I subclassed LinearLayoutManager to have it always snap to the top of the item.
This works in case the scroll event is fired, but when the RecyclerView is already in the right position, I don't get the onScrollStateChanged callback, as no scrolling occurs. Is there a way to get that event anyway? Like decide beforehand whether or not the RecyclerView needs to scroll or not?

Micky
  • 5,578
  • 7
  • 31
  • 55
  • you can check if the item (position) you want to scroll to is already on the screen before calling *LinearLayoutManager.smoothScrollToPosition()* – Bugdr0id Jul 07 '16 at 09:58
  • That's not sufficient, as it might be on the screen, but not at the top of the view, in which case scrolling will occur anyway. – Micky Jul 07 '16 at 10:09
  • How about layoutManager.findFirstCompletelyVisibleItemPosition() – SoroushA Jul 11 '16 at 19:09

2 Answers2

1

Hope the following code would help

if(LinearLayoutManager.findFirstCompletelyVisibleItem() == yourDesiredPosition) {
  //do your stuff
} else {
  LinearLayoutManager.scrollToPositionWithOffset(yourDesiredPosition, offset);
  //onScrollStateChanged would be trigger then.
}
Pip
  • 152
  • 4
  • No, this just tells me if the item I am looking for is completely visible on the screen. It does not tell me anything about the scroll position. The item might be visible, but at the bottom of the screen and the RecyclerView will scroll then. – Micky Jul 13 '16 at 07:45
  • I have an idea for your requirement. If all the adapter items are not covering the whole screen in that case scroll event will not be fired. Try adding a transparent view to your adapter layout and make it visible in the last item if whole screen is not covered. Give a fixed height to transparent view so that it will go out of the screen. – user320676 Jul 13 '16 at 15:53
  • Why would that mean that the scroll event will not be fired? Anyway I found a better solution than adding transparent views to my layout. See my answer above. – Micky Jul 15 '16 at 13:09
-1

I found the following solution myself:

// get the view the user selected
View view = mLayoutManager.findViewByPosition(index);
// get top offset 
int offset = view.getTop();
if (offset == 0) { // the view is at the top of the scrollview
    showDetailViewInternal(event);
} else {
    // scrolling
}
Micky
  • 5,578
  • 7
  • 31
  • 55