1

I have a RecyclerView with horizontal items. These items have fix 150dp height and 100dp width.

When the Fragment is loaded, than I set default items to this view.

After that, I make a Room getImages() call, when the result arrive than I rebuild this RecyclerView.

enter image description here

As you see in the GIF :

  • Default images loaded (2 with play button, 3 with pro image)
  • Add getImages() result
  • The result is inserted before the 1st default item

Play button cards have fix id actually ("-1") and pro have another fix ("0") and every image item have unique id.

The new item is added before the first item, and the user don't see it. The RecyclerView won't scroll to first item. There is any solution push the first item to right when a new one added to 1st place??

I tried the smoothScrollToPosition but it won't work after submitList() and maybe where is any better solution.

vihkat
  • 895
  • 3
  • 13
  • 28
  • Seems duplicate. https://stackoverflow.com/questions/38850591/adding-new-item-to-the-top-of-the-recyclerview – Toris Jan 26 '19 at 02:53
  • Show more code its hard to edit something you can not see remember. – Xenolion Jan 26 '19 at 11:53
  • If scroll to position is not working, you can reinitialize the adapter and set to recyclerview, which will scroll to top by default. – Kajol Chaudhary Jan 31 '19 at 07:37
  • Take a look at this [SO question](https://stackoverflow.com/questions/50293660/inserting-recyclerview-items-at-zero-position-always-stay-scrolled-to-top/50308230#50308230). Although I am not really happy with the accepted solution, if you don't use scroll bars, this may work for you. – Cheticamp Jan 31 '19 at 15:23
  • please paste the code of the adapter as well as the code where the getImages() is called and the recycle view is notified – Gaurang Goda Feb 01 '19 at 07:39

2 Answers2

1

All you have to do is use Recyclerview's smooth scroller

 smoothScroller = new LinearSmoothScroller(this) {
        @Override
        protected int getHorizontalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_ANY;
        }
    };

then when you want to scroll to first position of recyclerview

 smoothScroller.setTargetPosition(0);
 horizontalLayoutManagaer.startSmoothScroll(smoothScroller);
Aman Rawat
  • 375
  • 1
  • 11
-2

Try to use scrollToPosition(0) instead.

If that won't work, try whether adding a small delay is fixing it, like so:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        recyclerView.scrollToPosition(position); // Or maybe `smoothScrollToPosition()`
    }
}, 300); // Try a delay of 200 or 300 ms
Alex
  • 1,650
  • 16
  • 15