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

Android onTouchEvent 手勢方向判斷與八方向手勢框架

編輯:關於 Android 程式設計

滑一下螢幕,根據方向決定要彈出 PopupWindow、切換頁面還是關閉面板——這是很多互動的基礎。這裡實作一個可複用的框架:把角度計算與事件分發抽成工具類,再用一個抽象 BaseActivity 讓子類只要覆寫方向方法即可。

一、定義回呼介面

/**
 * 依滑動角度判斷方向後觸發的回呼
 */
public interface OnEventListener {

    void onLeft();        // ←
    void onTop();         // ↑
    void onRight();       // →
    void onBottom();      // ↓
    void onNortheast();   // ↗
    void onNorthwest();   // ↖
    void onSouthwest();   // ↙
    void onSoutheast();   // ↘

    void onTouch();                    // 手指觸及螢幕
    EventType onEventDistribute();     // 決定事件要不要繼續往下分發
}

二、角度計算與分發工具類

核心是把 360 度切成八等份,每份 45 度:

import android.view.MotionEvent;
import android.view.View;

public class OnEventTouchFactory {

    private static OnEventTouchFactory mCurrent;
    private static OnEventListener mListener;

    private int mLastEventX;
    private int mLastEventY;
    private EventType mType;
    private int mDistance = 50;          // 有效滑動的最小距離門檻
    private double cos;                  // 實際上是「角度」,命名沿用舊碼
    private double result;               // 滑動距離
    private EventType mCurrentType = null;

    public static OnEventTouchFactory getInstance(OnEventListener listener) {
        mListener = listener;
        if (mCurrent == null) {
            mCurrent = new OnEventTouchFactory();
        }
        return mCurrent;
    }

    public boolean onTouch(View v, MotionEvent event) {
        boolean status = false;
        mListener.onTouch();

        int eventX = (int) event.getX();
        int eventY = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastEventX = eventX;
                mLastEventY = eventY;
                mCurrentType = mListener.onEventDistribute();
                status = true;
                break;

            case MotionEvent.ACTION_MOVE:
                if (mCurrentType == EventType.normal) {
                    cos = getAngle(eventX, eventY, mLastEventX, mLastEventY);
                    result = getDistance(mLastEventX, mLastEventY, eventX, eventY);

                    /*
                     * 八方向的角度區間對照:
                     *   Left      ← : [157.5, 202.5]
                     *   Top       ↑ : [ 67.5, 112.5]
                     *   Right     → : [337.5, 360] 與 [0, 22.5]
                     *   Bottom    ↓ : [247.5, 292.5]
                     *   Northwest ↖ : [112.5, 157.5]
                     *   Northeast ↗ : [ 22.5,  67.5]
                     *   Southwest ↙ : [202.5, 247.5]
                     *   Southeast ↘ : [292.5, 337.5]
                     */
                    if ((cos >= 0 && cos <= 22.5) || (cos >= 337.5 && cos <= 360)) {
                        mType = EventType.left;
                    } else if (cos > 22.5 && cos <= 67.5) {
                        mType = EventType.nortwest;
                    } else if (cos > 67.5 && cos <= 112.5) {
                        mType = EventType.top;
                    } else if (cos > 112.5 && cos < 157.5) {
                        mType = EventType.northeast;
                    } else if (cos >= 157.5 && cos <= 202.5) {
                        mType = EventType.right;
                    } else if (cos > 202.5 && cos < 247.5) {
                        mType = EventType.southeast;
                    } else if (cos >= 247.5 && cos <= 292.5) {
                        mType = EventType.bottom;
                    } else if (cos > 292.5 && cos < 337.5) {
                        mType = EventType.southwest;
                    }
                    status = true;
                } else if (mCurrentType == EventType.complete) {
                    status = false;      // 事件被上層攔下,不再處理
                }
                break;

            case MotionEvent.ACTION_UP:
                if (result > mDistance) {     // 距離不足視為誤觸
                    if (mType == EventType.right)          mListener.onRight();
                    else if (mType == EventType.top)       mListener.onTop();
                    else if (mType == EventType.northeast) mListener.onNortheast();
                    else if (mType == EventType.nortwest)  mListener.onNorthwest();
                    else if (mType == EventType.left)      mListener.onLeft();
                    else if (mType == EventType.southeast) mListener.onSoutheast();
                    else if (mType == EventType.southwest) mListener.onSouthwest();
                    else if (mType == EventType.bottom)    mListener.onBottom();
                }
                status = true;
                break;
        }
        return status;
    }

    /** 求兩點連線與 X 軸正向的夾角,順時針為正 */
    public double getAngle(int px1, int py1, int px2, int py2) {
        int x = px2 - px1;
        int y = py2 - py1;
        if (x == 0 && y == 0) {
            return 0;
        }
        double hypotenuse = Math.sqrt(x * x + y * y);
        double cos = x / hypotenuse;
        double radian = Math.acos(cos);
        double angle = radian * 180 / Math.PI;

        if (y < 0) {
            angle = 180 + (180 - angle);
        } else if (y == 0 && x < 0) {
            angle = 180;
        }
        return angle;
    }

    /** 兩點距離 */
    public double getDistance(int x1, int y1, int x2, int y2) {
        double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
        return Math.sqrt(d);
    }

    public enum EventType {
        left, top, right, bottom,
        nortwest, southeast, southwest, northeast,
        normal,     // 事件繼續往下分發
        complete    // 事件完全被上層攔截
    }
}

三、抽象 BaseActivity

import com.example.base.OnEventTouchFactory.EventType;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public abstract class BaseActivity extends Activity
        implements OnTouchListener, OnEventListener {

    protected Class<?> mLeftClass = null;
    protected Class<?> mRightClass = null;
    protected Class<?> mTopClass = null;
    protected Class<?> mBottomClass = null;
    protected Class<?> mNortheastClass = null;
    protected Class<?> mNorthwestClass = null;
    protected Class<?> mSoutheastClass = null;
    protected Class<?> mSouthwestClass = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme();
        setContentView(getLayoutResID());
        configClass();
        initialization();
    }

    public abstract int getLayoutResID();

    public void setTheme() {}
    public void configClass() {}
    public void initialization() {}

    /*********************** onTouch ***********************/

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return OnEventTouchFactory.getInstance(this).onTouch(v, event);
    }

    @Override public void onLeft() {}
    @Override public void onTop() {}
    @Override public void onRight() {}
    @Override public void onBottom() {}
    @Override public void onNortheast() {}
    @Override public void onNorthwest() {}
    @Override public void onSouthwest() {}
    @Override public void onSoutheast() {}
    @Override public void onTouch() {}

    @Override
    public EventType onEventDistribute() {
        return EventType.normal;
    }

    /*********************** 常用方法 ***********************/

    public void startActivity(Class<?> cls) {
        startActivity(new Intent(this, cls));
    }

    public void startActivity(Class<?> cls, boolean isFinish) {
        startActivity(new Intent(this, cls));
        if (isFinish) {
            finish();
        }
    }

    public void startActivityWithAnimation(Class<?> cls, int enterAnim, int exitAnim) {
        startActivity(new Intent(this, cls));
        overridePendingTransition(enterAnim, exitAnim);
    }

    public void startActivity(Class<?> cls, boolean isFinish, int enterAnim, int exitAnim) {
        startActivity(new Intent(this, cls));
        if (isFinish) {
            finish();
        }
        overridePendingTransition(enterAnim, exitAnim);
    }

    public void ShowSToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    public void ShowLToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }
}

四、子類使用示範

import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.method.ScrollingMovementMethod;
import com.example.base.BaseActivity;
import com.example.base.OnEventTouchFactory.EventType;

public class MainActivity extends BaseActivity {

    @Override
    public int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public void initialization() {
        super.initialization();
        RelativeLayout parent = (RelativeLayout) findViewById(R.id.parent);
        TextView child = (TextView) findViewById(R.id.child);
        child.setMovementMethod(ScrollingMovementMethod.getInstance());
        parent.setOnTouchListener(this);      // 綁定手勢監聽
    }

    @Override public void onRight()     { super.onRight();     ShowSToast("right"); }
    @Override public void onTop()       { super.onTop();       ShowSToast("top"); }
    @Override public void onLeft()      { super.onLeft();      ShowSToast("left"); }
    @Override public void onBottom()    { super.onBottom();    ShowSToast("bottom"); }
    @Override public void onNortheast() { super.onNortheast(); ShowSToast("northeast"); }
    @Override public void onNorthwest() { super.onNorthwest(); ShowSToast("northwest"); }
    @Override public void onSoutheast() { super.onSoutheast(); ShowSToast("southeast"); }
    @Override public void onSouthwest() { super.onSouthwest(); ShowSToast("southwest"); }

    @Override
    public EventType onEventDistribute() {
        return super.onEventDistribute();
    }
}

BaseActivity 實作了 OnEventListener 並宣告為 abstract,子類只要綁定 setOnTouchListener(this),再按需求覆寫對應方向的方法即可,手勢判定邏輯完全不必重寫。

五、進階:事件衝突怎麼辦

上面這個版本適用於「整頁都是手勢區」的簡單場景。一旦頁面裡有可滾動的 ViewPager、ListView 或內嵌 Fragment,就會遇到事件衝突,這時要往下深入三層:

  • Activity:負責把事件分發給頂層 View,本身沒有 onInterceptTouchEvent。
  • ViewGroup:有 dispatchTouchEvent()(分發)與 onInterceptTouchEvent()(攔截)兩個方法,是解決衝突的關鍵。子 View 想搶事件時,父容器可在 onInterceptTouchEvent 回傳 true 把事件截下來。
  • View:只有 dispatchTouchEvent() 與 onTouchEvent(),靠 requestDisallowInterceptTouchEvent(true) 向父層申請「不要攔我的事件」。

實務上最常見的做法,是在自訂的 ViewPager 或 ScrollView 中判斷滑動方向:若判定為水平滑動,就呼叫 getParent().requestDisallowInterceptTouchEvent(true),讓父層不要搶走事件。這套機制理解清楚,複雜的手勢共存問題基本都能拆解。

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