RecyclerView smoothScroll to position in the center. android
Asked Answered
M

5

48

I am using a horizontal layout manager for my RecyclerView. I need to make RecyclerView in the next way: when click on some item - make smoothScrool to that position and put that item in the center of RecyclerView (if it possible, for example, 10 item from 20).

So, I have no problem with smoothScrollToPosition(), but how to put item than in the center of RecyclerView???

Thanks!

Moiety answered 16/7, 2016 at 22:15 Comment(0)
R
104

Yes it's possible.

By implementing RecyclerView.SmoothScroller's method onTargetFound(View, State, Action).

/**
 * Called when the target position is laid out. This is the last callback SmoothScroller
 * will receive and it should update the provided {@link Action} to define the scroll
 * details towards the target view.
 * @param targetView    The view element which render the target position.
 * @param state         Transient state of RecyclerView
 * @param action        Action instance that you should update to define final scroll action
 *                      towards the targetView
 */
abstract protected void onTargetFound(View targetView, State state, Action action);

Specifically in LinearLayoutManager with LinearSmoothScroller:

public class CenterLayoutManager extends LinearLayoutManager {

    public CenterLayoutManager(Context context) {
        super(context);
    }

    public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private static class CenterSmoothScroller extends LinearSmoothScroller {

        CenterSmoothScroller(Context context) {
            super(context);
        }

        @Override
        public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
            return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
        }
    }
}
Reata answered 23/9, 2016 at 6:49 Comment(8)
extends LinearSmoothScroller must override computeScrollVectorForPosition()Glyptography
Worked flawlessHouri
Perfect, for others, you just call recyclerView.smoothScrollToPosition(position); and don't forget to set the layout manager recyclerView.setLayoutManager(layoutManager);Varick
Where is that onTargetFound() function implemented?Carouse
But I did not understood exactly why you mentioned about this method onTargetFound() ?Tear
when call smoothScrollToPosition height all item decrease, why?Mammalian
Thank god in heaven you saved meDuplessis
A Perfect Solution Indeed. But, it's still not smooth enough. Is there a way to make it smoother ?Katelyn
L
66

Improvements to the answer - there is no need to override the LinearLayoutManager

From the previous answer:

public class CenterSmoothScroller extends LinearSmoothScroller {

    public CenterSmoothScroller(Context context) {
        super(context);
    }

    @Override
    public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
        return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
    }
}

Here how to use it:

RecyclerView.LayoutManager lm = new GridLayoutManager(...): // or whatever layout manager you need

...

RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());

smoothScroller.setTargetPosition(position);

lm.startSmoothScroll(smoothScroller);
Luttrell answered 13/12, 2018 at 6:41 Comment(7)
For others who are confused like I was, CenterSmoothScroller is a class found in the accepted answer.Blocking
Hallelujah! Spent half a day trying a bunch of convoluted ways to do this and your solution works perfectly. Thanks!Nellnella
How will I get the position while declaring the recyclerview? I need to get the item in center while the user scrolls the item using D-Pad. @user8944115Supererogate
this worked like a charm!! thanks if you don't find the class maybe you need update your dependencies, is under androidx.recyclerview.widget.LinearSmoothScrollerJuanajuanita
It's correct and easy solution. ThanksChryselephantine
For me, this doesnt work for the first and the last item in the recycler. Am I doing something wrong?Wahkuna
This method just slides an item to the center like a finger, so it is impossible to achieve the first or last item, just like your finger cannot do it.Avrom
T
19

Just in case someone needs the Kotlin equivalent of the class in the accepted answer.

class CenterLayoutManager : LinearLayoutManager {
    constructor(context: Context) : super(context)
    constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
        val centerSmoothScroller = CenterSmoothScroller(recyclerView.context)
        centerSmoothScroller.targetPosition = position
        startSmoothScroll(centerSmoothScroller)
    }

    private class CenterSmoothScroller(context: Context) : LinearSmoothScroller(context) {
        override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int = (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2)
    }
}
Transect answered 24/2, 2019 at 16:37 Comment(0)
P
5

Based on @Boda's answer, if you want to control smooth scroll speed (for better animation) you can use below:

class CenterLayoutManager : LinearLayoutManager {
    constructor(context: Context) : super(context)
    constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(
        context,
        orientation,
        reverseLayout
    )

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    )

    override fun smoothScrollToPosition(
        recyclerView: RecyclerView,
        state: RecyclerView.State,
        position: Int
    ) {
        val centerSmoothScroller = CenterSmoothScroller(recyclerView.context)
        centerSmoothScroller.targetPosition = position
        startSmoothScroll(centerSmoothScroller)
    }

    private class CenterSmoothScroller(context: Context) : LinearSmoothScroller(context) {
        override fun calculateDtToFit(
            viewStart: Int,
            viewEnd: Int,
            boxStart: Int,
            boxEnd: Int,
            snapPreference: Int
        ): Int = (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2)

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
            return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
        }
    }

    companion object {
        // This number controls the speed of smooth scroll
        private const val MILLISECONDS_PER_INCH = 150f
    }
}

Usage:

recyclerView.layoutManager = CenterLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
recyclerView.smoothScrollToPosition(selectedPosition)
Polychrome answered 17/4, 2021 at 9:10 Comment(0)
A
-3

since now(Feb 2019), I could easily use this code in ListView

(ListView)word_list_view.smoothScrollToPositionFromTop(your_item_index, center_position.y);

RecyclerView not verified, I guess would be the same.

Afghanistan answered 22/2, 2019 at 10:55 Comment(1)
Not available for RecyclerViewCoronach

© 2022 - 2024 — McMap. All rights reserved.