GestureDetector and GestureDetector.OnGestureListener

1 vote · 5 comments

That's a small example showing how GestureDetector and GestureDetector.OnGestureListener works. They can be used to recognize gestures like down, fling, long-press, scroll, show-press, single-tap-up, etc. Originally posted on anddev

raw ·
copy
· download
import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; import android.view.MotionEvent; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector; import android.widget.TextView; import android.graphics.Color; public class ScrollTest extends Activity implements OnGestureListener { private LinearLayout main; private TextView viewA; private GestureDetector gestureScanner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gestureScanner = new GestureDetector(this); main = new LinearLayout(this); main.setBackgroundColor(Color.GRAY); main.setLayoutParams(new LinearLayout.LayoutParams(320,480)); viewA = new TextView(this); viewA.setBackgroundColor(Color.YELLOW); viewA.setTextColor(Color.BLACK); viewA.setTextSize(16); viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80)); main.addView(viewA); setContentView(main); } @Override public boolean onTouchEvent(MotionEvent me) { return gestureScanner.onTouchEvent(me); } @Override public boolean onDown(MotionEvent e) { viewA.setText("-" + "DOWN" + "-"); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { viewA.setText("-" + "FLING" + "-"); return true; } @Override public void onLongPress(MotionEvent e) { viewA.setText("-" + "LONG PRESS" + "-"); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { viewA.setText("-" + "SCROLL" + "-"); return true; } @Override public void onShowPress(MotionEvent e) { viewA.setText("-" + "SHOW PRESS" + "-"); } @Override public boolean onSingleTapUp(MotionEvent e) { viewA.setText("-" + "SINGLE TAP UP" + "-"); return true; } }
Add a comment

5 Comments

The line "gestureScanner = new GestureDetector(this)" is deprecated. Please show how to fix it? Thanks

Reply · Sept. 5, 2012, 4:59 a.m.

change it to: gestureScanner = new GestureDetector(ScrollTest.this, this);

Reply · Nov. 24, 2012, 10:11 p.m.

I used the following:

gestureScanner = new GestureDetector(getBaseContext(), this);

Reply · Jan. 24, 2013, 6:14 p.m.

How know that which overlayitem long press? Please help.

Reply · Dec. 15, 2012, 5:30 p.m.

how can i detect the strokes of each alphabet letters and single digit numbers using gesture detector??

Reply · Feb. 24, 2013, 10:37 a.m.