LoginSignup
9
8

More than 5 years have passed since last update.

RecyclerView.smoothScrollToPositionの停止位置を変更する

Posted at

RecyclerViewのsmoothScrollToPositionが思ったところに止まらないので修正した時のメモ。
LinearLayoutManagerを使っています。

LinearLayoutManager.smoothScrollToPositionが使っているLinearSmoothScrollerですが、
既存の動作ではスクロールの向きによって、

  • SNAP_TO_START:Align child view's left or top with parent view's left or top)
  • SNAP_TO_END: Align child view's right or bottom with parent view's right or bottom)

を切り分けています。

どのスクロールの向きでも SNAP_TO_START を利用させたいので、
LinearLayoutManagerをカスタマイズしました。

public class CustomLayoutManager extends LinearLayoutManager {

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

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
            int position) {
        LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext()) {
                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        return DetailPageLayoutManager.this
                                .computeScrollVectorForPosition(targetPosition);
                    }

                    @Override
                    protected int getVerticalSnapPreference() {
                        return mTargetVector == null || mTargetVector.y == 0
                               ? SNAP_TO_ANY : SNAP_TO_START;
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
}

あとはRecyclerViewへセットして

recyclerView.setLayoutManager(new CustomLayoutManager(context);

smoothScrollToPositionを適当な時に呼び出します。

recyclerView.smoothScrollToPosition(position);
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8