66 lines
2.4 KiB
Java
66 lines
2.4 KiB
Java
package com.xscm.moduleutil.widget;
|
|
|
|
import android.view.View;
|
|
|
|
import androidx.recyclerview.widget.LinearLayoutManager;
|
|
import androidx.recyclerview.widget.RecyclerView;
|
|
|
|
public class InfintLinearLayoutManager extends LinearLayoutManager {
|
|
public InfintLinearLayoutManager(RecyclerView recyclerView) {
|
|
super(recyclerView.getContext(), HORIZONTAL, false);
|
|
}
|
|
|
|
@Override
|
|
public boolean canScrollHorizontally() {
|
|
return true; // 允许水平滑动
|
|
}
|
|
|
|
@Override
|
|
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
|
|
return super.scrollVerticallyBy(dy, recycler, state);
|
|
}
|
|
|
|
@Override
|
|
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
|
|
// 获取最后一个和第一个可见 item 的位置
|
|
int first = findFirstVisibleItemPosition();
|
|
int last = findLastVisibleItemPosition();
|
|
|
|
if (first == 0 && dx > 0) {
|
|
// 滑动到了最左边,现在往右滑,把最后一个 item 移动到前面复用
|
|
View lastView = getChildAt(last);
|
|
if (lastView != null) {
|
|
layoutScrapView(lastView, last, -1);
|
|
offsetChildrenHorizontal(-getDecoratedMeasuredWidth(lastView));
|
|
return dx;
|
|
}
|
|
} else if (last == getItemCount() - 1 && dx < 0) {
|
|
// 滑动到了最右边,现在往左滑,把第一个 item 移动到最后面复用
|
|
View firstView = getChildAt(first);
|
|
if (firstView != null) {
|
|
layoutScrapView(firstView, first, +1);
|
|
offsetChildrenHorizontal(+getDecoratedMeasuredWidth(firstView));
|
|
return dx;
|
|
}
|
|
}
|
|
|
|
return super.scrollHorizontallyBy(dx, recycler, state);
|
|
}
|
|
|
|
private void layoutScrapView(View view, int position, int direction) {
|
|
removeView(view);
|
|
|
|
// 复用的 item 设置为新的位置
|
|
int newPosition = direction > 0 ? getItemCount() - 1 : 0;
|
|
addView(view, direction > 0 ? getChildCount() : 0);
|
|
|
|
// 更新 adapter 的 position
|
|
RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams();
|
|
layoutDecoratedWithMargins(view,
|
|
0,
|
|
0,
|
|
getDecoratedMeasuredWidth(view),
|
|
getDecoratedMeasuredHeight(view));
|
|
}
|
|
}
|