我有这段代码来使用GestureDetector检测滚动手势。它工作,除了它检测滚动活动3次而不是一次。
如何只检测一次?它记录了滚动活动(log.i行)3次,并播放声音(mp.start)3次而不是一次....也导致我的应用程序强行关闭。
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;
}
答案 0 :(得分:2)
“onScroll()”将被多次调用。 它被调用的次数取决于用户完成的滚动操作。
如果您希望代码块在每个滚动操作的开头只运行一次,那么您必须添加一个条件,如下所示:
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;
}