Skip to content Skip to sidebar Skip to footer

Android Recyclerview Scroll To Top

This is my onCreate that handles the adapter, LinearLayoutManager and etc. I tried every single option to try to scroll it to the top but could not. I even tried to create my own c

Solution 1:

Did you try taskRecyclerView.getLayoutManager().scrollToPosition(0) or taskRecyclerView.scrollToPosition(your_position)?

RecyclerView does not implement any scrolling logic in taskRecyclerView.scrollToPosition(your_position) and taskRecyclerView.getLayoutManager().scrollToPosition(0) is more specific and it goes to specific index depending implemented layout, in your case is linear.

Solution 2:

Scrolling to specific items is a tricky part with RecyclerView but below code helps to scroll

Method for Smooth Scrolling

fun Context.getSmoothScroll(): LinearSmoothScroller {
        returnobject : LinearSmoothScroller(this) {
            overridefungetVerticalSnapPreference(): Int {
                return LinearSmoothScroller.SNAP_TO_START
            }
        }
    }

Apply Smooth scrolling to RecyclerView

fun RecyclerView.scrollToPositionSmooth(int: Int) {
        this.layoutManager?.startSmoothScroll(this.context.getSmoothScroll().apply {
            targetPosition = int
        })
    }

Apply Scrolling without Smooth to RecyclerView (Fast)

fun RecyclerView.scrollToPositionFast(position: Int) {
        this.layoutManager?.scrollToPosition(position)
    }

Code to use

itemFilteredRecyclerView.scrollToPositionFast(0) //Normal Scroll
itemFilteredRecyclerView.scrollToPositionSmooth(0) //Smooth Scroll

Extra Information: You can replace ..(0) with your position need to get scrolled.

Complete code: Link

Solution 3:

Adding the code below works too.

linearLayoutManager.setStackFromEnd(false);

Post a Comment for "Android Recyclerview Scroll To Top"