Detección de gestos


En este ejemplo vamos a ver como detectar gestos en la pantalla de nuestro dispositivo Android para lo cual usamos la clase onTouchEvent.




En este ejemplo detectamos cuando se produce una pulsación en la pantalla, dos o se realiza un desplazamiento vertical u horizontal.

public class ACapturar extends Activity implements OnGestureListener {  
//creates a Gesture Detector
private GestureDetector gd;
private float mLastTouchX;
        private float mLastTouchY;
       @Override
        public void onCreate(Bundle savedInstanceState)
{
        gd = new GestureDetector(this,this);
        //set the on Double tap listener
        gd.setOnDoubleTapListener(new OnDoubleTapListener()
        {
public boolean onDoubleTap(MotionEvent e){
activar_flash();
return true;
}

public boolean onDoubleTapEvent(MotionEvent e){
return false;
}

public boolean onSingleTapConfirmed(MotionEvent e){
ACapturar.this.openOptionsMenu();
return false;
}
        });
      
    }




@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
   switch (action) {
   case MotionEvent.ACTION_DOWN: {
       final float x = ev.getX();
       final float y = ev.getY();
     
       // Recordamos donde empezamos
       mLastTouchX = x;
       mLastTouchY = y;
       break;
   }
   case MotionEvent.ACTION_MOVE: {
       final float x = ev.getX();
       final float y = ev.getY();
       // Calculate the distance moved
       final float dx = x - mLastTouchX;
       final float dy = y - mLastTouchY;
       if((dx<-10)||(dy<-10)){
        //Aquí ponemos que queremos que haga si el desplazamiento
                                //es mayor de 10
       }else if ((dx>10)||(dy>10)){
        //Aquí ponemos que queremos que haga si el desplazamiento
                                //es mayor de 10
       }
       Log.d("MENSAJE","dx: "+dx+" x: "+x);
       Log.d("MENSAJE","dy: "+dy+" y: "+y);
       // Remember this touch position for the next move event
       mLastTouchX = x;
       mLastTouchY = y;
       // Invalidate to request a redraw
       break;
   }
   }
return gd.onTouchEvent(ev);//return the double tap events
}

public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return false;
}

public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}

public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}

public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}

public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}

public boolean onTouch(MotionEvent ev) {
   return true;
}

public void onInit(int status) {
// TODO Auto-generated method stub
}

No hay comentarios: