我有这段代码来使用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;
}
解决方法:
“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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。