3

I have this snippet of code to detect a scroll gesture using GestureDetector. It works, except it detects the scroll activity 3 times instead of once.

How can I make it detect only once? It logs the scrolls activity (log.i line) 3 times, and plays the sound (mp.start) 3 times instead of once too.... Also causes my application to force close.

 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { //get x and Y co-ordinates and log it as info. float x1 = e1.getX(); float y1 = e1.getY(); float x2 = e2.getX(); float y2 = e2.getY(); Log.i("Scroll_Gesture", "Scrolled from: (" + x1 + "," + y1 + " to " + x2 +"," + y2 + ")"); mp = MediaPlayer.create(this, R.raw.scroll_success); mp.start(); //start success page Intent intent = new Intent(this, ScrollSuccess.class); startActivity(intent); return false; } 
1
  • @Judith...did you ever get the answer for this? If help is greatly appreciated. Thanks! Commented Apr 13, 2016 at 1:17

1 Answer 1

4

"onScroll()" will be called multiple times. How many times it will be called would depend on the scroll action done by the user.

If you want your code block to run only once at the beginning of each scroll action then you would have to add a condition, something as below:

 float scrollstartX1, scrollStartY1; public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // get x and Y co-ordinates and log it as info. if (scrollstartX1 != e1.getX() || scrollStartY1 != e1.getY()) { scrollstartX1 = e1.getX(); scrollStartY1 = e1.getY(); //*************************************** //code run only once for a scroll action... //**************************************** } float x2 = e2.getX(); float y2 = e2.getY(); Log.i("Scroll_Gesture", "Scrolled from: (" + scrollstartX1 + "," + scrollStartY1 + " to " + x2 + "," + y2 + ")"); mp = MediaPlayer.create(this, R.raw.scroll_success); mp.start(); // start success page Intent intent = new Intent(this, ScrollSuccess.class); startActivity(intent); return false; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.