实现recyclerView点击item联动滑动居中

在实际开发尤其是电商项目的开发过程中,经常会用到分类的横向滑动列表,但是如果用普通的横向列表在点击的过程无法直接展示,这里我们就需要做到点击每一个item去联动滑动显示在可视化的界面中,直接上效果

所需效果图
import android.content.Context;
import android.util.DisplayMetrics;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Create by Carson on 2021/8/18.
 * 自定义recyclerView点击item滑动居中
 */
public class CenterLayoutManager extends LinearLayoutManager {

    static int lastPosition = 0;
    static int targetPosition = 0;

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

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

    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int lastPosition, int position) {
        CenterLayoutManager.lastPosition = lastPosition;
        CenterLayoutManager.targetPosition = position;
        smoothScrollToPosition(recyclerView, state, position);
    }

    public static class CenterSmoothScroller extends LinearSmoothScroller {
        private static float duration = 400f;

        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);
        }

        @Override
        protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
            float newDuration = duration / (Math.abs(targetPosition - lastPosition));
            return newDuration / displayMetrics.densityDpi;
        }

        @Override
        protected int calculateTimeForScrolling(int dx) {
            return super.calculateTimeForScrolling(dx);
        }
    }
}

接下来就是在adapter中进行引用了

CenterLayoutManager centerLayoutManager =
        new CenterLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
binding.recyclerTabSort.setLayoutManager(centerLayoutManager);
//这里省略adapter布局的方法
...
...
...
tabSortAdapter.setOnItemClickListener((adapter, view, position) -> {
    centerLayoutManager.smoothScrollToPosition(binding.recyclerTabSort,
            new RecyclerView.State(), indexPosition, position);
    if (indexPosition != position) {
        indexPosition = position;
    }
    tabSortAdapter.notifyDataSetChanged();
});

你可能感兴趣的:(实现recyclerView点击item联动滑动居中)