Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 RecyclerView 打造首頁輪播圖:SnapHelper 實戰

編輯:關於 Android 程式設計

先來看效果:

停在中央並自動翻頁。

一、需求緣起

最近接到一個需求,要做出類似上方那種自動翻頁的效果。一開始看到設計圖,直覺反應是用 ViewPager 來實作,但需求卻有個關鍵差異:必須以最左邊那張圖為對齊基準,也就是說左側的圖也要完整顯示,如下圖。

停在左側。

仔細思考後,ViewPager 似乎沒有這樣的能力(也可能是我沒找到相關資料),於是換了另一條路。

二、認識 SnapHelper

這裡要介紹 Google 在 24.2.0 版本(其實更早就已釋出)加入的 SnapHelper。它是對 RecyclerView 的功能擴充,有興趣的朋友可以研究它的原始碼。SnapHelper 的原理是實作 RecyclerView.OnFlingListener 的 onFling 回呼,讓 RecyclerView 具備類似 ViewPager 的對齊能力:無論怎麼滑動,最後都會停在某一頁的固定位置。

那它和 ViewPager 的差異在哪?ViewPager 無法一次連續滑動多張,而且對齊位置無法自訂(停左邊還是右邊),而 SnapHelper 這兩點都能做到。

先導入所需的套件,最低版本為 v7-24.2.0,版本過低會找不到這些類別:

compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'

系統內建了一個 LinearSnapHelper,它繼承自 SnapHelper,預設讓畫面停在中央。只要把它和 RecyclerView 綁定即可:

LinearSnapHelper mLinearSnapHelper = new LinearSnapHelper();
mLinearSnapHelper.attachToRecyclerView(mRecyclerview);

效果如下:

三、自訂對齊位置

SnapHelper 的能力不僅於此。若想改成停在左側或右側,不需要重新繼承 SnapHelper,直接繼承 LinearSnapHelper 並覆寫兩個方法即可:

· calculateDistanceToFinalSnap:拖拽或滑動結束時回呼,回傳長度為 2 的陣列 out,out[0] 為 x 軸、out[1] 為 y 軸,代表需要修正的偏移量。

· findSnapView:用來取得特定的子檢視,回傳 null 表示未取得任何檢視。

停在左側的完整實作:

public class LeftSnapHelper extends LinearSnapHelper {

    private OrientationHelper mHorizontalHelper;

    /**
     * 當拖拽或滑動結束時會回呼該方法,回傳長度為 2 的陣列,
     * out[0] 表示橫軸,out[1] 表示縱軸,這兩個值即為需要修正的偏移量
     */
    @Override
    public int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView) {
        // 由於是橫向滾動,這裡只考慮橫軸
        int[] out = new int[2];
        if (layoutManager.canScrollHorizontally()) {
            out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager));
        } else {
            out[0] = 0;
        }
        return out;
    }

    /** 計算偏移量 */
    private int distanceToStart(View targetView, OrientationHelper helper) {
        return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding();
    }

    @Override
    public View findSnapView(RecyclerView.LayoutManager layoutManager) {
        return findStartView(layoutManager, getHorizontalHelper(layoutManager));
    }

    /** 找出需要左對齊顯示的 view */
    private View findStartView(RecyclerView.LayoutManager layoutManager, OrientationHelper helper) {
        if (layoutManager instanceof LinearLayoutManager) {
            int firstChild = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
            int lastChild = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();

            if (firstChild == RecyclerView.NO_POSITION) {
                return null;
            }

            // 這是為了處理翻到最後一頁時,最後一個 Item 無法完整顯示的問題
            if (lastChild == layoutManager.getItemCount() - 1) {
                return layoutManager.findViewByPosition(lastChild);
            }

            View child = layoutManager.findViewByPosition(firstChild);
            if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2
                    && helper.getDecoratedEnd(child) > 0) {
                return child;
            } else {
                return layoutManager.findViewByPosition(firstChild + 1);
            }
        }
        return super.findSnapView(layoutManager);
    }

    /** 取得檢視方向 */
    private OrientationHelper getHorizontalHelper(@NonNull RecyclerView.LayoutManager layoutManager) {
        if (mHorizontalHelper == null) {
            mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager);
        }
        return mHorizontalHelper;
    }
}

若想改成停在右側,只需在上一份基礎上調整 findSnapView 與偏移量計算即可:

public class RightSnapHelper extends LinearSnapHelper {

    private OrientationHelper mHorizontalHelper;

    @Override
    public int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View targetView) {
        int[] out = new int[2];
        if (layoutManager.canScrollHorizontally()) {
            out[0] = distanceToEnd(targetView, getHorizontalHelper(layoutManager));
        } else {
            out[0] = 0;
        }
        return out;
    }

    /** 計算偏移量 */
    private int distanceToEnd(View targetView, OrientationHelper helper) {
        return helper.getDecoratedEnd(targetView) - helper.getEndAfterPadding();
    }

    @Override
    public View findSnapView(RecyclerView.LayoutManager layoutManager) {
        return findEndView(layoutManager, getHorizontalHelper(layoutManager));
    }

    /** 找出需要右對齊顯示的 view */
    private View findEndView(RecyclerView.LayoutManager layoutManager, OrientationHelper helper) {
        if (layoutManager instanceof LinearLayoutManager) {
            int lastChild = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
            if (lastChild == RecyclerView.NO_POSITION) {
                return null;
            }
            View child = layoutManager.findViewByPosition(lastChild);
            if (helper.getDecoratedStart(child) >= helper.getDecoratedMeasurement(child) / 2
                    && helper.getDecoratedStart(child) > 0) {
                return child;
            } else {
                return layoutManager.findViewByPosition(lastChild - 1);
            }
        }
        return super.findSnapView(layoutManager);
    }

    private OrientationHelper getHorizontalHelper(@NonNull RecyclerView.LayoutManager layoutManager) {
        if (mHorizontalHelper == null) {
            mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager);
        }
        return mHorizontalHelper;
    }
}

效果:

停在右側。

四、實作無限循環

要做到無限滑動,得在 Adapter 上做手腳,讓取得項目總數的方法回傳 Integer.MAX_VALUE:

@Override
public int getItemCount() {
    return Integer.MAX_VALUE;
}

接著在 onBindViewHolder 中取值時,用取餘運算對應回真實的資料索引:

@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
    Glide.with(mContext)
            .load(mList.get(position % mList.size()).getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .into(holder.ivImage);
    holder.tvName.setText(mList.get(position % mList.size()).getName());
}

五、加入自動輪播

做到這裡已完成約八成,接著要讓它能自動滾動。這裡參考 ViewPager 自動輪播的思路,使用 Timer 的週期性執行能力剛好勝任:

private int cnt = 2;                     // 目前最右邊顯示的 item position
private boolean isSlidingByHand = false; // 是否為使用者手動滑動
private boolean isSlidingAuto = true;    // 是否為自動滑動

timer.schedule(new TimerTask() {
    @Override
    public void run() {
        if (isSlidingAuto) {
            myHandler.sendEmptyMessage(CHANGE_ITEM);
        }
    }
}, 1000, 3000);

由於同時存在使用者手動滑動與 Timer 觸發的自動滑動兩種來源,還需要為 RecyclerView 加上監聽,藉此判斷目前是哪一種:

alRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int firstVisibleItemPosition = manager.findFirstVisibleItemPosition();

        switch (newState) {
            case SCROLL_STATE_IDLE:      // 靜止未滾動
                if (isSlidingByHand) {
                    Message msg = myHandler.obtainMessage();
                    msg.arg1 = firstVisibleItemPosition;
                    msg.what = CHANGE_ITEM;
                    myHandler.sendMessage(msg);
                }
                break;
            case SCROLL_STATE_DRAGGING:  // 正在被外部拖拽,一般為使用者手指滾動
                isSlidingByHand = true;
                isSlidingAuto = false;
                break;
            case SCROLL_STATE_SETTLING:  // 自動滾動中
                if (isSlidingByHand) {
                    isSlidingAuto = false;
                } else {
                    isSlidingAuto = true;
                }
                break;
        }
    }
});

最後統一交由 Handler 處理位移:

private static class MyHandler extends Handler {
    // 採用弱引用的方式,避免記憶體洩漏
    WeakReference<CenterActivity> weakReference;

    public MyHandler(CenterActivity mActivity) {
        this.weakReference = new WeakReference<>(mActivity);
    }

    @Override
    public void handleMessage(Message msg) {
        final CenterActivity mActivity = weakReference.get();
        Log.d(TAG, "handleMessage: handler is running");
        if (mActivity.isSlidingByHand) {
            mActivity.cnt = msg.arg1;
            mActivity.isSlidingByHand = false;
            mActivity.isSlidingAuto = true;
            mActivity.cnt += 2;
            // 讓 RecyclerView 平滑滾動
            mActivity.alRecyclerview.smoothScrollToPosition(++mActivity.cnt);
        } else {
            mActivity.alRecyclerview.smoothScrollToPosition(++mActivity.cnt);
        }
    }
}

做到這裡大致就完成了。不過還有一個細節值得留意:滾動過程並不是那麼順滑,原因尚待釐清,若知道答案的朋友歡迎留言交流。

參考資料

· OrientationHelper API
· Android 24.2.0 支援庫中 SnapHelper 的學習與使用

感謝以上資料的幫助。原始碼已上傳至 GitHub,有更好的想法也歡迎一起討論。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved