2

我有这段代码可以使用 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;
    }
4

1 回答 1

3

“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;
   }
于 2012-11-02T08:43:05.837 回答