AndroidのIO - GestureDetector
Androidは、
1. GestureDetectorを提供し、ジェスチャーを検知する
2. GestureLibraryを提供し、開発者がジェスチャーを追加し、対応するAPIを使い検知する
GestureDetector.onGestureListnerの一部イベント
- boolean onDown(MotionEvent e)
- boolean onFling(MotionEvent e)
- abstract void onLongPress(MotionEvent e)
- boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
- void onShowPress(MotionEvent e)
- boolean onSingleTapUp(MotionEvent e)
AndroidのGestureDetector実装流れ
サンプルコード
package com.example.liguofeng.gusturedetectorsample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener{ GestureDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); detector = new GestureDetector(this, this); } // Activity上のタッチイベントをGestureDetectorに処理依頼 @Override public boolean onTouchEvent(MotionEvent event) { return detector.onTouchEvent(event); } @Override public boolean onDown(MotionEvent e) { System.out.println("onDown"); Toast.makeText(this, "onDown", Toast.LENGTH_SHORT).show(); return false; } @Override public boolean onSingleTapUp(MotionEvent e) { System.out.println("onSingleTap"); Toast.makeText(this, "onSingleTap", Toast.LENGTH_SHORT).show(); return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { System.out.println("onScroll"); Toast.makeText(this, "onScroll", Toast.LENGTH_SHORT).show(); return false; } @Override public void onLongPress(MotionEvent e) { System.out.println("onLongPress"); Toast.makeText(this, "onLongPress", Toast.LENGTH_SHORT).show(); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { System.out.println("onFling"); Toast.makeText(this, "onFling", Toast.LENGTH_SHORT).show(); return false; } @Override public void onShowPress(MotionEvent e) { System.out.println("onShowPress"); Toast.makeText(this, "onShowPress", Toast.LENGTH_SHORT).show(); } }
※ イベント発生順
1. 短くクリック時 : onDown ⇒ onSingleTap
2. 長くクリック時 : onDown ⇒ onShowPress ⇒ onLongPress
3. スクロール時 : onDown ⇒ onScroll(複数回) ⇒ onFling