編輯:關於 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,有更好的想法也歡迎一起討論。
圖文深入解析 Android Activity 生命週期(含實作 Demo)
大家好,今天要和大家深入聊聊 Android 中 Activity 的生命週期。這個主題網路上談的人很多,但多數文章都只是照著 Android API 翻譯,講得比較籠統
魅族PRO 6與MX6有什麼不同?兩款機型的規格與定位對照
MX6開賣之後,很多人開始在兩者之間猶豫:預算足夠該直接上 PRO 6,還是MX6已經夠用?要回答這個問題,得先看兩台手機各自是怎麼被設計出來的。魅族MX6:把規格做滿的
Android 資料庫備份與還原實作:AsyncTask、FileChannel 與 Environment 一起用
本文示範一個實用的模式:在 UI Activity 中用 AsyncTask 開一條背景執行緒,於 onPause() 時備份 SQLite 資料庫、於 onResume
Android 自定義控件之組合控件開發學習筆記
來聊聊自定義組合控件,相信大家多少都接觸過。話不多說,直接開幹(哈~哈~): 看到這個,你可能覺得不就是寫個布局檔搞定嘛——沒錯,確實直接上布局就行,我只是用這個簡單的