import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;
import android.view.View;
/**
* 实现RecyclerView实现类似ViewPager的PageChangeListener监听
*/
public class RecyclerViewPageChangeListenerHelper extends RecyclerView.OnScrollListener {
private SnapHelper snapHelper;
private OnPageChangeListener onPageChangeListener;
private int oldPosition = -1;//防止同一Position多次触发
public RecyclerViewPageChangeListenerHelper(SnapHelper snapHelper, OnPageChangeListener onPageChangeListener) {
this.snapHelper = snapHelper;
this.onPageChangeListener = onPageChangeListener;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (onPageChangeListener != null) {
onPageChangeListener.onScrolled(recyclerView, dx, dy);
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
int position = 0;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//获取当前选中的itemView
View view = snapHelper.findSnapView(layoutManager);
if (view != null) {
//获取itemView的position
position = layoutManager.getPosition(view);
}
if (onPageChangeListener != null) {
onPageChangeListener.onScrollStateChanged(recyclerView, newState);
//newState == RecyclerView.SCROLL_STATE_IDLE 当滚动停止时触发防止在滚动过程中不停触发
if (newState == RecyclerView.SCROLL_STATE_IDLE && oldPosition != position) {
oldPosition = position;
onPageChangeListener.onPageSelected(position);
} else {
}
}
}
public interface OnPageChangeListener {
void onScrollStateChanged(RecyclerView recyclerView, int newState);
void onScrolled(RecyclerView recyclerView, int dx, int dy);
void onPageSelected(int position);
}
}
使用方法:
PagerSnapHelper snapHelper = new PagerSnapHelper() {
@Override
public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
return super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
}
};
snapHelper.attachToRecyclerView(mRecyclerView);
mRecyclerView.addOnScrollListener(new RecyclerViewPageChangeListenerHelper(snapHelper,new RecyclerViewPageChangeListenerHelper.OnPageChangeListener() {
onScrollStateChanged
onScrolled
onPageSelected
}
|