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

自訂 View 系列教程(一):六個必備工具類的完整導覽

編輯:關於 Android 程式設計

寫自訂 View 時,經常會用到 Android 內建的一批工具類。它們把拖拽、速度計算、滾動、手勢判斷等繁瑣細節都封裝好了;若全部自己實作,不僅工作量大,還容易埋 bug。因此在正式進入自訂 View 之前,先把這些工具逐一認識清楚。

本文要介紹的六位成員:Configuration、ViewConfiguration、GestureDetector、VelocityTracker、Scroller、ViewDragHelper。


Configuration

This class describes all device configuration information that can impact the resources the application retrieves.

顧名思義,它用來描述裝置的設定資訊:包含使用者層面的 locale、scaling,也包含裝置層面的輸入方式、螢幕尺寸與方向等。取得方式如下:

Configuration configuration = getResources().getConfiguration();

int countryCode = configuration.mcc;    // 國家碼
int networkCode = configuration.mnc;    // 網路碼

if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
    // 直向
} else {
    // 橫向
}

ViewConfiguration

名字只差一個 View,兩者卻沒有繼承關係。官方描述是:

Contains methods to standard constants used in the UI for timeouts, sizes, and distances.

也就是說,它提供了一批自訂控件常用的標準常量:尺寸、滑動距離、靈敏度等等。取得實例:

ViewConfiguration viewConfiguration = ViewConfiguration.get(context);

幾個常用的實例方法:

ViewConfiguration viewConfiguration = ViewConfiguration.get(context);

// 系統能辨識為「滑動」的最小距離,判斷是否為點擊時經常用到
int touchSlop = viewConfiguration.getScaledTouchSlop();

// Fling 速度的下限與上限
int minimumVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
int maximumVelocity = viewConfiguration.getScaledMaximumFlingVelocity();

// 是否有實體選單鍵
boolean isHavePermanentMenuKey = viewConfiguration.hasPermanentMenuKey();

另有幾個相當實用的靜態方法:

// 雙擊判定的時間窗內;超過即視為單擊
int doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();

// 按住多久後轉為長按狀態
int longPressTimeout = ViewConfiguration.getLongPressTimeout();

// 按鍵重複的間隔
int keyRepeatTimeout = ViewConfiguration.getKeyRepeatTimeout();

GestureDetector

手勢固然可以在 onTouchEvent() 中自行判斷,但 Android 已提供 GestureDetector 這個監聽類,能省下大量邊界判斷。

第一步:實作 OnGestureListener

private class GestureListenerImpl implements GestureDetector.OnGestureListener {

    // 觸摸螢幕時一定會觸發
    @Override
    public boolean onDown(MotionEvent e) {
        System.out.println("---> 手勢中的onDown方法");
        return false;
    }

    // 快速甩動
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        System.out.println("---> 手勢中的onFling方法");
        return false;
    }

    // 長按
    @Override
    public void onLongPress(MotionEvent e) {
        System.out.println("---> 手勢中的onLongPress方法");
    }

    // 拖動滾動
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        System.out.println("---> 手勢中的onScroll方法");
        return false;
    }

    // 按下後尚未移動或放開
    @Override
    public void onShowPress(MotionEvent e) {
        System.out.println("---> 手勢中的onShowPress方法");
    }

    // 輕點抬起
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        System.out.println("---> 手勢中的onSingleTapUp方法");
        return false;
    }
}

第二步:建立 GestureDetector 物件

GestureDetector gestureDetector = new GestureDetector(context, new GestureListenerImpl());

第三步:把 Touch 事件交給它處理

交給 Activity:

@Override
public boolean onTouchEvent(MotionEvent event) {
    return mGestureDetector.onTouchEvent(event);
}

交給個別 View:

mButton = (Button) findViewById(R.id.button);
mButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View arg0, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }
});

VelocityTracker

看名字就能猜到——速度追蹤。它用來計算觸摸事件的速率,是實作 Fling 效果時的必備夥伴。使用節奏固定為三步。

第一步:開始追蹤

private void startVelocityTracker(MotionEvent event) {
    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(event);
}

第二步:讀取速度

private int getScrollVelocity() {
    // 1000 代表以「每秒」為單位計算移動的像素數
    mVelocityTracker.computeCurrentVelocity(1000);
    int xVelocity = (int) mVelocityTracker.getXVelocity();
    return Math.abs(xVelocity);
}

同理可取得 Y 方向的 getYVelocity()。

第三步:釋放資源

private void stopVelocityTracker() {
    if (mVelocityTracker != null) {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }
}

Scroller

Scroller 出現頻率很高,這裡只強調三個容易誤解的重點。

第一點:scrollTo() 與 scrollBy() 的關係

public void scrollBy(int x, int y) {
    scrollTo(mScrollX + x, mScrollY + y);
}

由此可見 scrollBy() 只是換算後轉呼叫 scrollTo(),真正起作用的是後者。

第二點:scroll 的本質

scrollTo() 與 scrollBy() 移動的只是 View 的內容,View 本身及其背景並不移動。

第三點:座標方向與直覺相反

對一個 TextView 呼叫 scrollTo(0, 25),裡面的文字會往上跑,而不是往下——為什麼?因為呼叫該方法會觸發重繪:

public void invalidate(int l, int t, int r, int b)

其中 l、t、r、b 代表 View 原來的座標,最終會走到:

tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
p.invalidateChild(this, tmpr);

注意第一行:原來的 l 與 r 都減去了 scrollX,t 與 b 都減去了 scrollY。也就是說 scrollX 為正值時,重繪後 View 的可視寬度反而縮短;scrollY 為正值時高度反而縮短。結論就是:scrollTo(0, 25) 的效果與我們的直覺恰好相反。scrollBy() 同理。


ViewDragHelper

專案中常有「讓使用者拖動內部某個 View」的需求。若自己在 onInterceptTouchEvent() 與 onTouchEvent() 中處理,得應付拖拽移動、越界修正、多指按下的 pointerId 管理、加速度判斷等一堆細節。ViewDragHelper 正是為此而生,它提供了一組輔助方法與狀態記錄。QQ 的側滑菜單、Navigation Drawer 的邊緣滑動,都可以用它是現。

以下範例展示最常見的用法:

/**
 * ViewDragHelper 使用示例
 */
public class MyLinearLayout extends LinearLayout {

    private ViewDragHelper mViewDragHelper;

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViewDragHelper();
    }

    private void initViewDragHelper() {
        mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {

            // 決定哪些子 View 可被拖動
            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return true;
            }

            // 水平方向的越界修正
            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                int fixedLeft;
                View parent = (View) child.getParent();
                int leftBound  = parent.getPaddingLeft();
                int rightBound = parent.getWidth() - child.getWidth() - parent.getPaddingRight();
                if (left < leftBound) {
                    fixedLeft = leftBound;
                } else if (left > rightBound) {
                    fixedLeft = rightBound;
                } else {
                    fixedLeft = left;
                }
                return fixedLeft;
            }

            // 垂直方向的越界修正
            @Override
            public int clampViewPositionVertical(View child, int top, int dy) {
                int fixedTop;
                View parent = (View) child.getParent();
                int topBound    = getPaddingTop();
                int bottomBound = getHeight() - child.getHeight() - parent.getPaddingTop();
                if (top < topBound) {
                    fixedTop = topBound;
                } else if (top > bottomBound) {
                    fixedTop = bottomBound;
                } else {
                    fixedTop = top;
                }
                return fixedTop;
            }

            // 監聽拖動狀態變化
            @Override
            public void onViewDragStateChanged(int state) {
                super.onViewDragStateChanged(state);
                switch (state) {
                    case ViewDragHelper.STATE_DRAGGING: System.out.println("STATE_DRAGGING"); break;
                    case ViewDragHelper.STATE_IDLE:     System.out.println("STATE_IDLE");     break;
                    case ViewDragHelper.STATE_SETTLING: System.out.println("STATE_SETTLING"); break;
                }
            }

            // 成功捕獲 View
            @Override
            public void onViewCaptured(View capturedChild, int activePointerId) {
                super.onViewCaptured(capturedChild, activePointerId);
                System.out.println("ViewCaptured");
            }

            // 放開 View
            @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                super.onViewReleased(releasedChild, xvel, yvel);
                System.out.println("ViewReleased");
            }
        });
    }

    // 事件攔截交給 ViewDragHelper
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mViewDragHelper.shouldInterceptTouchEvent(ev);
    }

    // Touch 事件交給 ViewDragHelper
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        mViewDragHelper.processTouchEvent(ev);
        return true;
    }
}

從這個例子可以看出,ViewDragHelper 是作用在 ViewGroup 上(例如 LinearLayout),而非直接作用於被拖動的子 View。這其實不難理解——子 View 在版面中的位置,本就是由其父容器決定的。

範例中 ViewDragHelper 主要做了四件事:

  1. 接管 ViewGroup 的事件攔截(onInterceptTouchEvent)。
  2. 接管 ViewGroup 的 Touch 事件(onTouchEvent)。
  3. 處理拖動過程中的邊界越界(clampViewPositionHorizontal/Vertical)。
  4. 監聽拖動狀態的變化(onViewDragStateChanged)。

除此之外,它還能實作抽屜拉伸、松手後自動回位等更進階的效果——只要在 onViewReleased() 中呼叫 settleCapturedViewAt() 並搭配 Scroller 即可。


把這六個工具摸熟,我們就可以正式開始寫自訂 View 了。

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