2014-07-25 20 views
1

這是我第一次使用Android手勢。我試圖用我在這個網站上找到的以下方法調用swipeRight()和swipeLeft()。Android手勢 - onDown有時僅被稱爲

SwipeTouchListener.java

public class SwipeTouchListener implements View.OnTouchListener { 

    private final GestureDetector gestureDetector; 

    public SwipeTouchListener(Context context) { 
     gestureDetector = new GestureDetector(context, new GestureListener()); 
    } 

    @Override 
    public boolean onTouch(View view, MotionEvent motionEvent) { 
     gestureDetector.onTouchEvent(motionEvent); 
     return true; 
    } 

    public void onSwipeLeft() { 

    } 

    public void onSwipeRight() { 

    } 

    private class GestureListener extends GestureDetector.SimpleOnGestureListener{ 

     private static final int SWIPE_DISTANCE_THRESHOLD = 100; 
     private static final int SWIPE_VELOCITY_THRESHOLD = 100; 

     @Override 
     public boolean onDown(MotionEvent e) { 
      return true; 
     } 

     @Override 
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
      float distanceX = e2.getX() - e1.getX(); 
      float distanceY = e2.getY() - e1.getY(); 
      if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { 
       if (distanceX > 0) 
        onSwipeRight(); 
       else 
        onSwipeLeft(); 
       return true; 
      } 
      return false; 
     } 
    } 

} 

而且在我的活動,我把下面的方法和覆蓋onSwipeLeft()和onSwipeRight(),並顯示在兩個敬酒消息。

chartFlipper.setOnTouchListener(new SwipeTouchListener(this){ 

    @Override 
    public void onSwipeLeft() { 
     Toast.makeText(DashboardActivity.this, "Swipe Left", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onSwipeRight() { 
     Toast.makeText(DashboardActivity.this, "Swipe Right", Toast.LENGTH_SHORT).show(); 
    } 
}); 

但問題是,我只能在極少數情況下看到吐司消息。我在onDown方法中添加了一個斷點,並發現它只會被調用幾次(就像20次中的一次)。

編輯:我在ViewFlipper上調用了這個方法。

編輯2:我在ViewFlipper中顯示一個餅圖和一個條形圖作爲2個視圖。我剛剛發現,在圖表上滑動並不會觸摸。有沒有辦法解決這個問題?

回答

0
在你的方法

@Override 
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
     float distanceX = e2.getX() - e1.getX(); 
     float distanceY = e2.getY() - e1.getY(); 
     if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { 
      if (distanceX > 0) 
       onSwipeRight(); 
      else 
       onSwipeLeft(); 
      return true; 
     } 
     return false; 
    } 

你必須和用戶覆蓋的條件距離應該比你在很多情況下有另一個AND條件SWIPE_VELOCITY_THRESHOLD這可能會在任何情況下不正確的和SWIPE_DISTANCE_THRESHOLD距離大,這可能低於閾值。因此,只有在距離大於閾值且速度也大於閾值速度的情況下才能看到結果。請嘗試降低這些值,並且您會更頻繁地看到結果。