1

When I add new data to my RecycleView, if I'm at the top of the view then I get scrolled down a tiny bit. How do I correctly scroll to the top of a RecycleView? I have tried:

boolean isAtTop = !mRecyclerView.canScrollVertically(-1);
mRecyclerAdapter.updateMessageItemDataList(mMessageItems);
if (isAtTop)
    mRecyclerView.scrollToPosition(0);

But that does nothing (I still get scrolled down a tiny bit). I searched on Stack overflow and found the following, which still doesn't do anythnig:

boolean isAtTop = !mRecyclerView.canScrollVertically(-1);
mRecyclerAdapter.updateMessageItemDataList(mMessageItems);
if (isAtTop)
    ((LinearLayoutManager)mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(0, 0);

isAtTop is always being identified correctly, but my attempts to scroll back up to the top never work. Has anyone ever encountered a similar issue.

It's really weird because I can scroll to the bottom of the view correctly using

mRecyclerView.scrollToPosition(mRecyclerAdapter.getItemCount() - 1);
CaptainForge
  • 1,365
  • 7
  • 21
  • 46
  • Maybe cause it needs to be `if(!isAtTop)` – Vucko Jun 29 '16 at 15:47
  • No, I only want to scroll to the top if it was already at the top prior to adding new data. – CaptainForge Jun 29 '16 at 15:56
  • Ah, okay, I misunderstood then. Did you try [this question](http://stackoverflow.com/questions/32159724/scroll-to-top-in-recyclerview-with-linearlayoutmanager)? – Vucko Jun 29 '16 at 15:59
  • Yep! That's where I got the ```.scrollToPositionWithOffset(0, 0)``` from. – CaptainForge Jun 29 '16 at 16:00
  • The thing that comes to mind is that it takes some time to update the data in the list, and scroll is being called before that, data gets added, and scroll was already called. Try to test my assumption by adding a button and putting the scroll to the top code in it's onClick method. If so, then you know the root of your problem and we can proceed solving it further. – Vucko Jun 29 '16 at 16:03

2 Answers2

0

Maybe this will be useful (this works in my case):

final LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
myRecycler.setLayoutManager(mLinearLayoutManager);
myRecycler.setHasFixedSize(true);

...
anyButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mLinearLayoutManager != null) {
             myRecycler.scrollToPositionWithOffset(0, 0);
        }
    }
});
Gaston Flores
  • 2,457
  • 3
  • 23
  • 42
0

working in my case #salamtempe

ActionButon.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if (new LinearLayoutManager(getActivity()) != null) {
            mRecyclerView.smoothScrollToPosition(0);
        }
    }
});