簡單的實現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()取餘來獲取實際的記錄的索引值即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章