39

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!

Jorge Gil
  • 3,881
  • 3
  • 33
  • 54
Stan Malcolm
  • 2,420
  • 4
  • 28
  • 46

6 Answers6

91

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);
        }
    }
}
Floern
  • 31,495
  • 23
  • 98
  • 115
user3680200
  • 987
  • 8
  • 8
48

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);
Arpit J.
  • 882
  • 10
  • 17
王 能
  • 501
  • 4
  • 4
  • 1
    For others who are confused like I was, `CenterSmoothScroller` is a class found in the accepted answer. – rjr-apps Feb 14 '19 at 23:20
  • 1
    Hallelujah! Spent half a day trying a bunch of convoluted ways to do this and your solution works perfectly. Thanks! – mjp66 Mar 18 '20 at 23:25
  • 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. @user8944115 – Aravind Apr 28 '20 at 07:31
11

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)
    }
}
Boda
  • 239
  • 2
  • 11
0

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.

Corxit Sun
  • 595
  • 5
  • 7
0

For me this approach worked:

recyclerView.smoothScrollToPosition(desiredPostion);
MiguelD
  • 377
  • 1
  • 4
  • 15
0

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)
PinkRabbits
  • 126
  • 2
  • 9