Android游戲開發(fā)之十一:View中如何進(jìn)行手勢識別
很多網(wǎng)友發(fā)現(xiàn)Android中手勢識別提供了兩個類,由于Android 1.6以下的版本比如cupcake中無法使用android.view.GestureDetector,而 android.gesture.Gesture是Android 1.6開始支持的,考慮到仍然有使用Android 1.5固件的網(wǎng)友,就來看下兼容性更強(qiáng)的android.view.GestureDetector。在 android.view.GestureDetector類中有很多種重載版本,下面我們僅提到能夠自定義在View中的兩種方法,分別為 GestureDetector(Context context, GestureDetector.OnGestureListener listener) 和GestureDetector(Context context, GestureDetector.OnGestureListener listener, Handler handler) 。我們可以看到***個參數(shù)為Context,所以我們想附著到某View時,最簡單的方法就是直接從超類派生傳遞Context,實(shí)現(xiàn) GestureDetector里中提供一些接口。
下面我們就以實(shí)現(xiàn)手勢識別的onFling動作,在CwjView中我們從View類繼承,當(dāng)然大家可以從TextView等更高層的界面中實(shí)現(xiàn)觸控。
- class CwjView extends View {
- private GestureDetector mGD;
- public CwjView(Context context, AttributeSet attrs) {
- super(context, attrs);
- mGD = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- int dx = (int) (e2.getX() - e1.getX()); //計算滑動的距離
- if (Math.abs(dx) > MAJOR_MOVE && Math.abs(velocityX) > Math.abs(velocityY)) { //降噪處理,必須有較大的動作才識別
- if (velocityX > 0) {
- //向右邊
- } else {
- //向左邊
- }
- return true;
- } else {
- return false; //當(dāng)然可以處理velocityY處理向上和向下的動作
- }
- }
- });
- }
- /*提示大家上面僅僅探測了Fling動作僅僅實(shí)現(xiàn)了onFling方法,這里相關(guān)的還有以下幾種方法來實(shí)現(xiàn)具體的可以參考我們以前的文章有詳細(xì)的解釋:
- boolean onDoubleTap(MotionEvent e)
- boolean onDoubleTapEvent(MotionEvent e)
- boolean onDown(MotionEvent e)
- void onLongPress(MotionEvent e)
- boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
- void onShowPress(MotionEvent e)
- boolean onSingleTapConfirmed(MotionEvent e)
- boolean onSingleTapUp(MotionEvent e)
- */
- //接下來是重點(diǎn),讓我們的View接受觸控,需要使用下面兩個方法讓GestureDetector類去處理onTouchEvent和onInterceptTouchEvent方法。
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- mGD.onTouchEvent(event);
- return true;
- }
- @Override
- public boolean onInterceptTouchEvent(MotionEvent event) {
- return mGD.onTouchEvent(event);
- }
- }
本節(jié)關(guān)于View中手勢識別的內(nèi)容就講這些。大家知道,很多Android設(shè)備都提供了重力感應(yīng)器和加速度感應(yīng)器,而稍好些的設(shè)備還具備陀螺儀感應(yīng)器,提供測試角速度功能。下一節(jié)將為大家講解重力感應(yīng)知識。