venerdì 13 aprile 2012

Swipe gesture

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.TextView;

public class FlingActivity extends Activity {
    private TextView gestureEvent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gestureEvent = (TextView)findViewById(R.id.test);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
     // TODO Auto-generated method stub
       return gestureDetector.onTouchEvent(event);
    }

    SimpleOnGestureListener simpleOnGestureListener
      = new SimpleOnGestureListener(){


     @Override
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
       float velocityY) {
      String swipe = "";
      float sensitvity = 50;
     
      // TODO Auto-generated method stub
      if((e1.getX() - e2.getX()) > sensitvity){
       swipe += "Swipe Left\n";
      }else if((e2.getX() - e1.getX()) > sensitvity){
       swipe += "Swipe Right\n";
      }else{
       swipe += "\n";
      }
     
      if((e1.getY() - e2.getY()) > sensitvity){
       swipe += "Swipe Up\n";
      }else if((e2.getY() - e1.getY()) > sensitvity){
       swipe += "Swipe Down\n";
      }else{
       swipe += "\n";
      }
     
      gestureEvent.setText(swipe);
     
      return super.onFling(e1, e2, velocityX, velocityY);
     }
      };
    
      GestureDetector gestureDetector
      = new GestureDetector(simpleOnGestureListener);
   }