2017-10-21 227 views
1

我有一個叫做ProfileFragment.java的片段,我想通過調用類OnSwipeTouchListener來監聽觸摸手勢。如何在片段中使用setOnTouchListener?

下面是代碼ProfileFragment.java一個片段:

rootLayout.setOnTouchListener(new OnSwipeTouchListener(ProfileFragment.this) { 

      @Override 
      public void onSwipeTop() { 
       super.onSwipeTop(); 
       //folder_gridview.setVisibility(View.INVISIBLE); 

       // do something 
      } 
}); 

從上面的代碼中,我得到這個錯誤:

OnSwipeTouchListener (android.content.Context) in OnSwipeTouchListener cannot be applied to (com.mydomain.sample.ProfileFragment)

這裏是OnSwipeTouchListener.java類的代碼:

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 = 1; 
     private static final int SWIPE_VELOCITY_THRESHOLD = 1; 

     @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() { 
    } 
} 

我能夠讓上面的代碼在一個活動上工作,但不能讓它在一個片段上工作。我如何得到它在一個片段上工作?

回答

1

您必須通過OnSwipeTouchListener上的context參數,而是傳遞不會從context繼承的片段ProfileFragment.this

您應該通過getActivity()爲PARAM您OnSwipeTouchListener這樣的:

rootLayout.setOnTouchListener(new OnSwipeTouchListener(getActivity()) { 
    /*rest of your code*/ 
});