編輯:關於 Android 程式設計
網路上的滑輪(Wheel)元件不少,各種改寫版本都有,但實際用起來總覺得哪裡不夠順手,乾脆自己動手做一個時間選擇用的滑輪元件,順手開源出來。
專案位址:https://github.com/apple317/displayview

上圖是 Demo 跑出來的效果:四個滑輪並排,分別對應月、日、小時、分鐘,中間以兩條分隔線標出當前選取值,上下帶有漸層陰影讓它有立體感。
界面在 XML 中以水平 LinearLayout 排列四個自訂的 WheelView,用 layout_weight 平均分配寬度:
<LinearLayout android:orientation="horizontal" android:padding="10dp"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<com.apple.disview.WheelView android:id="@+id/fast_month"
android:layout_width="0dip" android:layout_height="100dp"
android:layout_weight="1.0" />
<com.apple.disview.WheelView android:id="@+id/fast_day"
android:layout_width="0dip" android:layout_height="100dp"
android:layout_weight="1.0" />
<com.apple.disview.WheelView android:id="@+id/fast_hours"
android:layout_width="0dip" android:layout_height="100dp"
android:layout_weight="1.0" />
<com.apple.disview.WheelView android:id="@+id/fast_mintue"
android:layout_width="0dip" android:layout_height="100dp"
android:layout_weight="1.0" />
</LinearLayout>
程式碼側則先準備四組字串陣列作為資料源:HOUR_STRING 是 00 到 23,MINTUE_STRING 是 00 到 59,DAY_STRING 是 01 到 31,MONTH_STRING 是 01 到 12。
初始化每個滑輪時的步驟大致一致:
wheel_month = (WheelView) mottom.findViewById(R.id.fast_month);
wheel_month.setTag("month"); // 標記用途
wheel_month.setAdapter(new ArrayWheelAdapter(MONTH_STRING)); // 綁定資料
wheel_month.setCurrentItem(wheel_month.getCurrentVal("02")); // 設定當前值
wheel_month.setCyclic(true); // 允許循環滾動
wheel_month.setLabel("月"); // 單位標籤
wheel_month.addChangingListener(wheelChangeListener); // 值變化監聽
wheel_month.addScrollingListener(wheelScrolledListener, null); // 滾動狀態監聽
wheel_month.setleftCheck(true); // 左側陰影
這裡有兩個設計意圖值得說明。第一,每個滑輪都透過 setTag() 打上 month、day、hours、minute 的標記,這樣多個滑輪就能共用同一組監聽器,在回呼中靠 tag 分辨是哪一個在變動。第二,getCurrentVal("02") 這種以「值」反查「索引」的方法很實用,因為外部拿到的往往是使用者上次選擇的字串,而不是下標。
監聽器本身很輕量,主要用來記錄滾動狀態:
OnWheelScrollListener wheelScrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
}
};
wheelScrolled 這個旗標的用途是:滑輪在飛滾過程中會連續觸發值變化,若每次都去更新關聯的其他滑輪(例如日期要隨月份調整天數),會造成效能浪費甚至互相觸發。實務上通常等 onScrollingFinished 之後再統一處理联动。
整個元件的原理其實不複雜:建立一個自訂 View,透過手勢與滾動監聽取得滑動距離,再用 StaticLayout 把一疊文字畫在畫布上,依偏移量決定顯示哪幾項。
幾個關鍵成員如下:
private static final int SCROLLING_DURATION = 500; // 對齊動畫時長 private static final int MIN_DELTA_FOR_SCROLLING = 1; private static final int DEF_VISIBLE_ITEMS = 3; // 預設可見項數 private static float TEXT_SIZE = 24; private WheelAdapter adapter; private int currentItem; private int visibleItems = DEF_VISIBLE_ITEMS; private int itemHeight; private TextPaint itemsPaint; // 列表項畫筆 private TextPaint valuePaint; // 當前值畫筆 private StaticLayout valueLayout; private boolean isScrollingPerformed; private int scrollingOffset; // 關鍵:當前滾動偏移量 private GestureDetector gestureDetector; private Scroller scroller; private int lastScrollY; private boolean isCyclic = true;
scrollingOffset 是整個元件的靈魂。手指滑動時,doScroll() 把距離累加到 scrollingOffset,再除以單項高度算出跨過了幾項,藉此更新 currentItem,最後把餘數留在 scrollingOffset 裡,讓下次繪圖能從正確的像素位置繼續畫。
private void doScroll(int delta) {
scrollingOffset += delta;
int count = scrollingOffset / getItemHeight();
int pos = currentItem - count;
if (isCyclic && adapter.getItemsCount() > 0) {
while (pos < 0) pos += adapter.getItemsCount();
pos %= adapter.getItemsCount();
} else {
pos = Math.max(pos, 0);
pos = Math.min(pos, adapter.getItemsCount() - 1);
}
int offset = scrollingOffset;
if (pos != currentItem) {
setCurrentItem(pos, false);
} else {
invalidate();
}
scrollingOffset = offset - count * getItemHeight();
}
isCyclic 的意義就在這裡:開啟時索引可以無限循環,滑到底會接回第一項;關閉時則把位置夾在合法範圍內。
觸摸事件交給 GestureDetector 處理,onScroll 負責跟手拖動,onFling 負責快滑後的慣性:
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
startScrolling();
doScroll((int) -distanceY);
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
lastScrollY = currentItem * getItemHeight() + scrollingOffset;
int maxY = isCyclic ? 0x7FFFFFFF : adapter.getItemsCount() * getItemHeight();
int minY = isCyclic ? -maxY : 0;
scroller.fling(0, lastScrollY, 0, (int) -velocityY / 2,
0, 0, minY, maxY);
setNextMessage(MESSAGE_SCROLL);
return true;
}
慣性由 Scroller 計算,再由 animationHandler 逐幀取出位移量餵給 doScroll()。當 Scroller 跑完,justify() 會接手做最後的「吸附」:判斷偏移量是否超過半格,超過就補一段短動畫對齊到最近的整項,否則直接結束滾動。這個吸附手感是滑輪元件好不好的關鍵。
private final int MESSAGE_SCROLL = 0;
private final int MESSAGE_JUSTIFY = 1;
private Handler animationHandler = new Handler() {
public void handleMessage(Message msg) {
scroller.computeScrollOffset();
int currY = scroller.getCurrY();
int delta = lastScrollY - currY;
lastScrollY = currY;
if (delta != 0) doScroll(delta);
if (Math.abs(currY - scroller.getFinalY()) < MIN_DELTA_FOR_SCROLLING) {
currY = scroller.getFinalY();
scroller.forceFinished(true);
}
if (!scroller.isFinished()) {
animationHandler.sendEmptyMessage(msg.what);
} else if (msg.what == MESSAGE_SCROLL) {
justify();
} else {
finishScrolling();
}
}
};
onDraw() 依序做三件事:初始化畫筆、建立 StaticLayout、把內容畫上去。
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
initResourcesIfNecessary();
createLayouts();
drawValue(canvas);
canvas.restore();
// ... 繪製中間的漸層高亮與上下分隔線
}
createLayouts() 用 buildText() 把當前值上下各若干項拼成一個多行字串,再放進 StaticLayout。這樣做的好處是:整疊文字只需一次 draw 呼叫,滾動時只要平移畫布即可,不必逐項計算座標。
private String buildText(boolean useCurrentValue) {
StringBuilder itemsText = new StringBuilder();
int addItems = visibleItems / 2 + 1;
for (int i = currentItem - addItems; i <= currentItem + addItems; i++) {
String text = getTextItem(i);
if (text != null) itemsText.append(text);
if (i < currentItem + addItems) itemsText.append("\n");
}
return itemsText.toString();
}
drawValue() 中的 canvas.translate 是視覺效果的來源——把畫布往上推一個「首行高度」,再疊上 scrollingOffset,當前值就會隨滾動平滑移動:
int top = valueLayout.getLineTop(1); canvas.translate(this.getWidth() / 3, -top + scrollingOffset + itemHeight); valueLayout.draw(canvas);
至於中間那圈立體感,則是用 LinearGradient 搭配半透明 Paint 畫出來的,上下兩段深色漸層加上一條淺色分隔線,視覺上就足夠了。
整支元件的對外 API 可以歸成四類:資料(setAdapter)、狀態(setCurrentItem、setCyclic、setVisibleItems)、外觀(setLabel、setViewHeight、setleftCheck)與事件(addChangingListener、addScrollingListener)。要新增一個滑輪,只要在 XML 擺上元件、在程式碼餵一組字串陣列即可,成本很低。
若日後要優化,我認為有兩處可以再打磨:一是 onDraw 中每次都 new 出 Shader 與 Paint 物件,在滾動時會造成不必要的 GC 壓力,應提到成員變數複用;二是月份與日期的联动目前需要外部自行協調,把它內建進元件會更好用。
Dagger2 依賴注入圖文全解:從入門到進階的完整教程
Dagger2 依賴注入圖文全解 廢話不多說,直接談談我對它的理解。Dagger2 是 Android 平台上相當知名的依賴注入框架。在當前 Android 開發中,M
從源碼看 Android View 如何保存與恢復狀態
自定義控件是每個 Android 開發者的必經之路。走到某一步就會撞上同一個問題:狀態怎麼存? 如果不管這件事,用戶橫屏一下、或者按了返回再進來,控件就回到初始模樣——T
Android 自訂 Toolbar 使用方法詳解
Toolbar 是 Android 中常用的頂部導覽列元件,可取代傳統 ActionBar,並提供更高的自訂彈性。本文從基本用法出發,再說明如何封裝自訂 Toolbar。
Android 接入支付寶支付:從申請商家帳號到 RSA 簽章配置的完整流程
行動支付的普及,讓「付款」幾乎成了每個商業類 App 的標配。過去支付模組不在我負責的範圍內,總覺得那是塊硬骨頭;直到這次專案由我承接訂單模組,真正動手之後才發現——只要