5

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?

Community
  • 1
  • 1
Jonny Wright
  • 1,119
  • 4
  • 20
  • 38

3 Answers3

6
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.

I.K.
  • 61
  • 2
1

this may help:

adapter.notifyItemInserted(position);
recyclerView.scrollToPosition(position);
Androidss
  • 47
  • 11
0
  mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int testimonycount = mAdapter.getItemCount();
            int lastVisiblePosition =
                    linearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the
            // user is at the bottom of the list, scroll to the bottom
            // of the list to show the newly added message.
            if (lastVisiblePosition == -1 ||
                    (positionStart >= (testimonycount - 1) &&
                            lastVisiblePosition == (positionStart - 1))) {
                recipeRecyclerview.scrollToPosition(positionStart);
            }
        }
  • 1
    Welcome to Stackoverflow. Its best to add some description to your answer to show how your proposed code solves the problem. – bcperth Nov 13 '18 at 10:55