Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use RecyclerView.scrollToPosition() to move the position to the top of current view?

People also ask

How do you tell the RecyclerView to start at a specific item position?

If onLayoutChildren is called by RecyclerView, it checks if adapters itemCount is already > 0. If true, it calls scrollToPositionWithOffset() . So I can tell immediately what position should be visible, but it will not be told to LayoutManager before position exists in Adapter. Show activity on this post.

How do I move items in RecyclerView?

Android Swipe To Delete. Swipe to delete feature is commonly used to delete rows from a RecyclerView. In order to implement Swipe to delete feature, we need to use the ItemTouchHelper utility class.

How do I scroll to the bottom of my recycler view?

Recyclerview scroll to bottom using scrollToPositon. After setting the adapter, then call the scrollToPosition function to scroll the recycler view to the bottom.


If I understand the question, you want to scroll to a specific position but that position is the adapter's position and not the RecyclerView's item position.

You can only achieve this through the LayoutManager.

Do something like:

rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

Below link might solve your problem:

https://stackoverflow.com/a/43505830/4849554

Just create a SmoothScroller with the preference SNAP_TO_START:

RecyclerView.SmoothScroller smoothScroller = new 
LinearSmoothScroller(context) {
   @Override protected int getVerticalSnapPreference() {
       return LinearSmoothScroller.SNAP_TO_START;
   }
};

Now you set the position where you want to scroll to:

smoothScroller.setTargetPosition(position);

And pass that SmoothScroller to the LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);

If you want to scroll to a specific position and that position is the adapter's position, then you can use StaggeredGridLayoutManager scrollToPosition

   StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
   staggeredGridLayoutManager.scrollToPosition(10);
   recyclerView.setLayoutManager(staggeredGridLayoutManager);

This is the Kotlin code snippet but you can just get the point for scrolling to the item by position properly. The point is to declare the member variable for the layout manager and use its method to scroll.

lateinit var layoutManager: LinearLayoutManager

fun setupView() {
    ...

    layoutManager = LinearLayoutManager(applicationContext)
    mainRecyclerView.layoutManager = layoutManager

    ...
}

fun moveToPosition(position: Int) {
    layoutManager.scrollToPositionWithOffset(position, 0)
}