在實際開發(fā)尤其是電商項目的開發(fā)過程中瓶珊,經(jīng)常會用到分類的橫向滑動列表蚤吹,但是如果用普通的橫向列表在點擊的過程無法直接展示,這里我們就需要做到點擊每一個item去聯(lián)動滑動顯示在可視化的界面中,直接上效果
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中進(jìn)行引用了
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();
});