2013年12月8日星期日

實現 GestureDetector.OnGestureListener 檢測手勢

這個示例代碼通過實現 GestureDetector.OnGestureListener 檢測用戶的手勢操作:
實現 GestureDetector.OnGestureListener 檢測手勢
實現 GestureDetector.OnGestureListener 檢測手勢

package com.example.androidgesturedetector;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

public class MainActivity extends Activity {

 String info;
 TextView infoView;
 private GestureDetectorCompat myGestureDetectorCompat;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // setContentView(R.layout.activity_main);
  infoView = new TextView(this);
  setContentView(infoView);

  info = "";
  infoView.setText(info);

  myGestureDetectorCompat = new GestureDetectorCompat(this,
    myOnGestureListener);
 }

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

 GestureDetector.OnGestureListener myOnGestureListener = new 
   GestureDetector.OnGestureListener() {

  @Override
  public boolean onDown(MotionEvent e) {
   info = "onDown - " + e.getX() + " : " + e.getY() + "\n";
   infoView.setText(info);
   return false;
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   info += "onFling - " + "\n" + " e1 - " + e1.getX() + " : "
     + e1.getY() + "\n" + " e2 - " + e2.getX() + " : "
     + e2.getY() + "\n" + " velocityX = " + velocityX + "\n"
     + " velocityY = " + velocityY + "\n";
   infoView.setText(info);
   return false;
  }

  @Override
  public void onLongPress(MotionEvent e) {
   info += "onLongPress - " + e.getX() + " : " + e.getY() + "\n";
   infoView.setText(info);
  }

  @Override
  public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
    float arg3) {
   info += "onScroll\n";
   infoView.setText(info);
   return false;
  }

  @Override
  public void onShowPress(MotionEvent e) {
   info += "onShowPress - " + e.getX() + " : " + e.getY() + "\n";
   infoView.setText(info);
  }

  @Override
  public boolean onSingleTapUp(MotionEvent e) {
   info += "onSingleTapUp - " + e.getX() + " : " + e.getY() + "\n";
   infoView.setText(info);
   return false;
  }
 };

}


相關帖子:
- 手勢檢測 GestureDetector.SimpleOnGestureListener

沒有留言:

發佈留言