概要
做一个自动滑动的列表,用于展示聊天记录或者通知栏信息等,还是使用主流的RecyclerView来做。网上有很多案例,但当手动滑动时会一直无限循环,数据重复的出现,如果想要自动滑动时能无限循环,手动滑动时又能滑到底呢?本案例就解决这种手动滑动和自动滑动无缝衔接的问题。
思路
1、重写RecyclerView,通过scrollBy和postDelayed进行定时移动到达自动滑动目的
2、RecyclerView添加addOnScrollListener,进行手指按下滑动和抬起监听,用于判断是手动滑动还是自动滑动。
3、修改adapter的itemCount
4、接下来上代码
实现方案
1、重写 RecyclerView:
public class SocllRecyclerView extends RecyclerView {
private Autoaaview autoview;
private boolean running;
private boolean canrun;
private static final int Timea = 40;//控制滚动的速度,值越大速度越慢
public SocllRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
autoview = new Autoaaview(this);
}
public SocllRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private class Autoaaview implements Runnable{
WeakReference<SocllRecyclerView> myScrViewWeakReference;
public Autoaaview(SocllRecyclerView myScrView) {
myScrViewWeakReference = new WeakReference<>(myScrView);
}
@Override
public void run() {
SocllRecyclerView myScrView = myScrViewWeakReference.get();
if (myScrView.canrun&&myScrView.running){
myScrView.scrollBy(2,2);
myScrView.postDelayed(myScrView.autoview,Timea);
}
}
}
//开始滚动
public void start(){
if (running)
stop();
running = true;
canrun = true;
postDelayed(autoview,Timea);
}
//停止滚动
public void stop() {
running = false;
removeCallbacks(autoview);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
return super.onTouchEvent(e);
}
}
2、适配器 MyscrviewAdapter
public class MyscrviewAdapter ext