2016-02-20 58 views
0

我想這GestureListener添加到我的recyclerview:安卓:RecyclerView setOnTouchListener使得滾動壞

public class OnSwipeTouchListener implements OnTouchListener { 

    private final GestureDetector gestureDetector; 

    public OnSwipeTouchListener (Context ctx){ 
     gestureDetector = new GestureDetector(ctx, new GestureListener()); 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     return gestureDetector.onTouchEvent(event); 
    } 

    private final class GestureListener extends SimpleOnGestureListener { 

     private static final int SWIPE_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) { 
      boolean result = false; 
      try { 
       float diffY = e2.getY() - e1.getY(); 
       float diffX = e2.getX() - e1.getX(); 
       if (Math.abs(diffX) > Math.abs(diffY)) { 
        if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { 
         if (diffX > 0) { 
          onSwipeRight(); 
         } else { 
          onSwipeLeft(); 
         } 
        } 
        result = true; 
       } 
       else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) { 
        if (diffY > 0) { 
         onSwipeBottom(); 
        } else { 
         onSwipeTop(); 
        } 
       } 
       result = true; 

      } catch (Exception exception) { 
       exception.printStackTrace(); 
      } 
      return result; 
     } 
    } 

    public void onSwipeRight() { 
    } 

    public void onSwipeLeft() { 
    } 

    public void onSwipeTop() { 
    } 

    public void onSwipeBottom() { 
    } 
} 

但如果我這個touchlistener添加到我的recyclerview,滾動是壞的。如果用戶滾動並擡起手指,它不會進一步平滑滾動。我如何添加這個OnTouchListener並保持「平滑滾動」?

回答

0

當觸摸事件被分派到視圖時,總是調用onTouchListener's onTouch。因此請嘗試在onTouch()方法中添加此項,並且您還可以使用event.getAction()上的開關,並根據您的要求將案例設置爲MotionEvent.ACTION_UP,MotionEvent.ACTION_DOWN

if(event.getAction() == MotionEvent.ACTION_UP){ 

     // Do what you want 
     return true; 
    } 
    return false; 
+0

我不知道你是什麼意思。問題是,如果用戶舉起手指,列表不會進一步滾動。所以突然停下來看起來很糟糕。 – blueman3399

+0

YAH [這](http://stackoverflow.com/questions/12802969/change-android-smooth-scroll-behaviour-on-click)答案可能會幫助你...看看...任何嘗試混合解決方案 –