1

I am trying to scroll to first completely visible item while scrolling and I am doing following:

recyclerView.addOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager layoutManager = ((LinearLayoutManager) recyclerView
                    .getLayoutManager());

            int position = layoutManager.findFirstCompletelyVisibleItemPosition();

            if(position>0){
                recyclerView.smoothScrollToPosition(position);
                Log.e(TAG, "onScrolled: just called smooth scroll >> "+position );
            }
        }
    });

I am getting correct position of firs completely visible item but scroll to it [trying to scroll it to the initial position of visible portion of the screen] is not working. I tried to achieve it by doing following:

1.

recyclerView.smoothScrollToPosition(position);

2.

layoutManager.smoothScrollToPosition(recyclerView, null, position);

they make no change!! I googled for solution but I am not getting the right one. Please, suggest me how can I achieve that ?

Ngima Sherpa
  • 1,397
  • 1
  • 13
  • 34
  • 1
    In other words, you are trying to get the `RecyclerView` to "snap" to a view similar to the behavior of `ViewPager`? And because you're using `findFirstCompletelyVisibleItemPosition`, I assume you're trying to snap the top edge of the list item to the top edge of the `RecyclerView`? – kris larson Dec 01 '16 at 14:37
  • 1
    If so, have a look at these answers: http://stackoverflow.com/q/26370289/4504191 – kris larson Dec 01 '16 at 14:39
  • Thanks @krislarson, It worked for me. – Ngima Sherpa Dec 02 '16 at 04:29
  • You may answer so I could mark as solution – Ngima Sherpa Dec 02 '16 at 04:33
  • 1
    I am happy to refer you to a solution that works. Sometimes you just have to know the best search term to use (i.e."snap"). You can just upvote the answer that worked for you, that will help the community. Cheers – kris larson Dec 02 '16 at 10:38

1 Answers1

0

Use SnapHelper

SnapHelper snapHelper = new GravitySnapHelper(Gravity.START); 
snapHelper.attachToRecyclerView(startRecyclerView);

For more details, read this article: https://rubensousa.github.io/2016/08/recyclerviewsnap

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
Wahab Khan Jadon
  • 875
  • 13
  • 21