简单的实现RecyclerView自动滚动的方法

当RecyclerView内容过多,超出屏幕的时候,需要让它自己滚动展示数据,尤其是某些Android设备处于高处,或是不可被触摸点击的,这样的情况下,让其自己滚动展示数据尤为重要了!
自动滚动的方案有很多种,目前比较常见又最简单的一种是:继承至RecyclerView,并实现runnable方法,每间隔10ms(delayTime)就去执行scrollby(x,y)方法,其中delayTime和x,y的值决定了滚动速度。
public class AutoPollRecyclerView extends RecyclerView {
    private static final long delayTime= 50;//间隔多少时间后执行滚动
    AutoPollTask autoPollTask;//滚动线程
    private boolean running; //是否正在滚动
    private boolean canRun;//是否可以自动滚动,根据数据是否超出屏幕来决定

    public AutoPollRecyclerView(Context context) {
        super(context);
    }

    public AutoPollRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        autoPollTask = new AutoPollTask(this);//实例化滚动刷新线程
    }

    static class AutoPollTask implements Runnable {
        private final WeakReference<AutoPollRecyclerView> mReference;

        //使用弱引用持有外部类引用 防止内存泄漏
        public AutoPollTask(AutoPollRecyclerView reference) {
            this.mReference = new WeakReference<AutoPollRecyclerView>(reference);
        }

        @Override
        public void run() {
            AutoPollRecyclerView recyclerView = mReference.get();//获取recyclerview对象
            if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
                recyclerView.scrollBy(2, 2);//注意scrollBy和scrollTo的区别
                //延迟发送
                recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.delayTime);
            }
        }
    }

    //开启:如果正在运行,先停止->再开启
    public void start() {
        if (running)
            stop();
        canRun = true;
        running = true;
        postDelayed(autoPollTask, delayTime);
    }

    public void stop() {
        running = false;
        removeCallbacks(autoPollTask);
    }
}
上面代码实现了最基本的滚动功能,但有时候Adnroid设备可以触摸的话,而当前recyclerview正在滚动,又去滑动它,那就会造成界面错乱,数据错乱了,所以还需要重写拦截onTouchEvent方法,当触摸到recyclerview的时候,即在ACTION_DOWN的时,停止滚动线程,在ACTION_UP、ACTION_CANCEL时再开启线程。
 @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (running)
                    stop();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                if (canRun)
                    start();
                break;
        }
        return super.onTouchEvent(e);
    }

以上代码基本来源网络。
最后在设置itemCount的数量的时候不要返回集合的size,常见的返回Integer.MAX_VALUE,然后在获取数据的时候,用position和data.size()取余来获取实际的记录的索引值即可。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值