Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView in setReverseLayout scroll to top (or bottom)

Apologies for the potentially misleading title but I had no idea how to word it. If anyone else thinks they can come up with something better please feel free to edit.

I have a RecyclerView which I populate with Firebase records. To make the most recent records show at the top of the list, I have set my RecvlerView to setReverseLayout(true) and setStackFromEnd(true) as suggested here. This works great when the number of items fit within the screen space - the rest of the items smoothly scroll down, giving space for the new item which fades in, as shown below.

Good

The problem is when the existing items take up all of the screen space, the new item is added 'above' the others and the RecyclerView effectively expands above the top of the screen, so to see the new item I need to pull or scroll the list down manually. Another GIF below;

Bad

How can I overcome this?

like image 962
Jonny Wright Avatar asked Feb 12 '17 12:02

Jonny Wright


2 Answers

final int SCROLLING_UP = -1;
boolean scrollToNewTop = !recyclerView.canScrollVertically(SCROLLING_UP);
//TODO update adapter here
adapter.notifyItemInserted(adapter.getItemCount() - 1);
if (scrollToNewTop) {
    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
}

This will scroll you up if you are at the very top and leave everything as it is if you're somewhere in a middle saving from annoying jumping.

like image 174
I.K. Avatar answered Nov 27 '22 00:11

I.K.


this may help:

adapter.notifyItemInserted(position);
recyclerView.scrollToPosition(position);
like image 32
Androidss Avatar answered Nov 26 '22 22:11

Androidss