95

I have a fragment in which there is RecyclerView with LinearLayoutManager in which there are CardView items. There is a floating action button on clicking which the items should scroll to top. I have tried using scrollToPosition as well as scrollToPositionWithOffset with RecyclerView and also with LinearLayoutManager as shown below. But it has no effect at all. Why is this so? Can anyone please help me out.

And i have placed the RecyclerView directly inside the SwipeRefreshView in the xml file. I am calling setFloatingActionButton as soon as set adapter to RecyclerView.

 public void setFloatingActionButton(final View view) {
    float = (android.support.design.widget.FloatingActionButton) getActivity().findViewById(R.id.float);
    float.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    mRecyclerView.smoothScrollToPosition(0);


            android.support.design.widget.Snackbar.make(view, "Scrolled to Top", android.support.design.widget.Snackbar.LENGTH_SHORT)
                    .setAction("Ok", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                            llm.scrollToPosition(0);

                        }
                    })
                    .setActionTextColor(getActivity().getResources().getColor(R.color.coloLink))
                    .show();
        }
    });
}
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
SRBhagwat
  • 1,491
  • 2
  • 16
  • 21
  • Try `mLayoutManager.scrollToPositionWithOffset(0, 0);` – Antrromet Aug 22 '15 at 19:07
  • yeah i have tried this .But this has no effect too just like scrollToPosition. – SRBhagwat Aug 22 '15 at 19:09
  • Thats strange, because even I had a similar layout as yours. I had a `RecyclerView` with layout manager and that was placed in a `SwipeRefreshview`, and that worked for me. – Antrromet Aug 22 '15 at 19:11
  • Is there any problem if i call scrollToPosition as soon as i set adapter to recyclerview? – SRBhagwat Aug 22 '15 at 19:15
  • But by default when you set the adapter to the `RecyclerView` for the very first time, the list is scrolled to the top. So you need not call `scrollToPosition` explicitly. Anyway try running it after some delay, by using some delay and check. `http://developer.android.com/reference/android/view/View.html#postDelayed(java.lang.Runnable, long)` – Antrromet Aug 22 '15 at 19:19
  • 1
    Now i placed mlayoutmanager.scrollToPositionWithOffset(0,0); outside the method setFloatingAction button and it works fine !!! – SRBhagwat Aug 22 '15 at 19:20
  • So is there any way i can use scroll to top when i click Floating Action Button? – SRBhagwat Aug 22 '15 at 19:27

9 Answers9

187

Continuing from above comments, ideally, replacing

mRecyclerView.smoothScrollToPosition(0);

in the onClick of the floating action button with

mLayoutManager.scrollToPositionWithOffset(0, 0);

should work. You can also remove the SnackBar code, because you don't need it anyways. So, all in all your above method should look like

public void setFloatingActionButton(final View view) {
    float actionButton = (android.support.design.widget.FloatingActionButton) getActivity()
            .findViewById(R.id.float);
    actionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView
                    .getLayoutManager();
            layoutManager.scrollToPositionWithOffset(0, 0);
        }
    });
}

And if you say that the above doesnt work, then test if the onClick() is even being called or not. Try adding a log message in it and see if its printed.

Antrromet
  • 15,294
  • 10
  • 60
  • 75
  • Yeah i actually got it by removing calls from other fragments to this method. I placed fab creation in onCreate() method directly.Its working completely fine now. – SRBhagwat Aug 22 '15 at 19:43
  • And with snackbar its not working. Thats fine as there is no need of snackbar. – SRBhagwat Aug 22 '15 at 19:51
  • This solution works only in first fragment.If i call setFloatingActionActionButton from both the fargments then scrollToTop works only in second fragment but not in first fragment.I am extending second fragment from first fragment.Can you plz help? – SRBhagwat Aug 24 '15 at 17:40
  • Why are you calling this in the fragment in the first place, and not from the activity? – Antrromet Aug 24 '15 at 19:55
  • How do i access mRecyclerView in the mainactivity and set mRecyclerView.scrollToPosition(0) from the main activity? i am new to android as well as java.I am learning lot of things while developing this app:)Thank You – SRBhagwat Aug 25 '15 at 15:17
  • Can you plz tell me how do i access mRecyclerView, which is in all the fragments, from main activity and set scrollToPosition(0) so that on clicking FAB in any fragment the recycler view scrolls to top?? – SRBhagwat Aug 26 '15 at 04:23
  • Can you explain whether your mRecyclerView is placed in the fragments or the main activity? If possible please post the code for the fragments and the main activity, so that I can understand what the flow of your app is. – Antrromet Aug 27 '15 at 01:14
  • mRecyclerView is placed in the fragments.Each fragment has an instance of recyclerview but not FAB as it is placed in activity_main.So can you please tell me how do i access mRecyclerView, which is in all the fragments, from main activity and set scrollToPosition(0) so that on clicking FAB in any fragment the recycler view scrolls to top?? – SRBhagwat Aug 29 '15 at 13:48
  • You must have an instances of the fragments in your MainActivity. Use that to access the `mRecyclerView`. – Antrromet Aug 29 '15 at 18:48
  • This is not working when the recylerview is set reverselayout() and stackfromend(). – Codevalley Jul 31 '16 at 16:29
19

Using the method smoothScrollToPosition() worked for me with the newest Android version.

layoutManager.smoothScrollToPosition(mRecyclerView, null, 0);
gunner_dev
  • 357
  • 2
  • 11
6

Call 'scrollToPosition(0)' using this:

public void scrollToPosition(final int position) {
    if (mRecyclerView != null) {
        getHandler().post(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.scrollToPosition(position);
                if (position == 0) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                    layoutManager.scrollToPositionWithOffset(0, 0);
                    mScrollView.fullScroll(View.FOCUS_UP);
                }
            }
        });
    }
}
Lee Hounshell
  • 842
  • 9
  • 10
4

If you don't want smooth scroll this will work with any LayoutManager:

myRecyclerView.getLayoutManager().scrollToPosition(0);
Martin Braun
  • 10,906
  • 9
  • 64
  • 105
2

In Kotlin

        // Scroll to the top of the list
        GlobalScope.launch(Dispatchers.Main) {
            delay(200)
            if (binding.rateList.size > 1) {
                //binding.recyclerView.smoothScrollToPosition(0)
                binding.recyclerView.layoutManager?.scrollToPosition(0)
            }
Thiago
  • 12,778
  • 14
  • 93
  • 110
1

In my case, the requirement was to populate the view in reverse order, which made the layout show the bottom view of the scroll view

layoutManager.smoothScrollToPosition(mRecyclerView, null, 'last_index') didn't really help.

My problem was resolved when I made the recycler view to show the child at the last position

recyclerView.scrollToPosition(length-1)

aQwus jargon
  • 133
  • 3
  • 18
Antroid
  • 391
  • 4
  • 15
0

The above solutions didn't work for me coz my recycler view was inside the NestedScrollView. So this solution worked for me.

nestedScroll.smoothScrollTo(0,recycler.top)
Denny
  • 991
  • 12
  • 20
  • 1
    It's a bad idea to have a RecyclerView in a NestedScrollView. – TimB Apr 14 '21 at 00:01
  • 1
    Recyclerview inside NestedScrollview results list not recycled but keep on adding. There is definitely lags in the application. Better to use Recyclerview alone. – Sunil Aug 31 '21 at 10:11
0

Some time user uses NestedScrollView for the NestedScrollView we can use below code .

 /*Scrolls NestedScrollView to the top of screen.*/
        viewBinding.scrollview.fullScroll(View.FOCUS_UP)

May be it can help to somebody in future.

0

in Kotlin you can create Extension for RecyclerView:

fun RecyclerView.scrollToUp() = this.layoutManager?.scrollToPosition(0)

Now you can call this function on your RecyclerView:

yourRecyclerView.scrollToUp()
onesector
  • 361
  • 5
  • 18