Friday, May 4, 2012

Using GestureDetector with SimpleOnGestureListener


Using GestureDetector with SimpleOnGestureListener

GestureDetector.SimpleOnGestureListener is a convenience class to extend when you only want to listen for a subset of all the gestures.

Using GestureDetector with SimpleOnGestureListener

package com.exercise.AndroidSimpleGesture;

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 AndroidSimpleGestureActivity extends Activity {

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.GestureEvent);
   }
  
   @Override
public boolean onTouchEvent(MotionEvent event) {
 // TODO Auto-generated method stub
    return gestureDetector.onTouchEvent(event);
}

SimpleOnGestureListener simpleOnGestureListener
   = new SimpleOnGestureListener(){

 @Override
 public boolean onDoubleTap(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onDoubleTap: \n" + e.toString());
  return super.onDoubleTap(e);
 }

 @Override
 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
   float velocityY) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onFling: \n" + e1.toString() + "\n" + e2.toString() +"\n"
    + "velocityX= " + String.valueOf(velocityX) + "\n"
    + "velocityY= " + String.valueOf(velocityY) + "\n");
  return super.onFling(e1, e2, velocityX, velocityY);
 }

 @Override
 public void onLongPress(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onLongPress: \n" + e.toString());
  super.onLongPress(e);
 }

 @Override
 public boolean onSingleTapConfirmed(MotionEvent e) {
  // TODO Auto-generated method stub
  gestureEvent.setText("onSingleTapConfirmed: \n" + e.toString());
  return super.onSingleTapConfirmed(e);
 }

   };
  
   GestureDetector gestureDetector
   = new GestureDetector(simpleOnGestureListener);
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />
  
   <TextView
       android:id="@+id/GestureEvent"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" />

</LinearLayout>

No comments: