Простой Swipe-листенер для View (Fragment или Activity)

  1. private GestureDetector gestureDetector;
  2. View.OnTouchListener gestureListener;
  3.  
  4. public void setSwipeListener(View v) {
  5.     if (v == null) return;
  6.     gestureDetector = new GestureDetector(this, new SwipeGestureDetector());
  7.     gestureListener = new View.OnTouchListener() {
  8.         public boolean onTouch(View v, MotionEvent event) {
  9.             return gestureDetector.onTouchEvent(event);
  10.         }
  11.     };
  12.     v.setOnTouchListener(gestureListener);
  13. }
  14.  
  15. private void onLeftSwipe() { }
  16.  
  17. private void onRightSwipe() {
  18.     onBackPressed();
  19. }
  20.  
  21. private class SwipeGestureDetector extends SimpleOnGestureListener {
  22.     private static final int SWIPE_MIN_DISTANCE = 50;
  23.     private static final int SWIPE_MAX_OFF_PATH = 200;
  24.     private static final int SWIPE_THRESHOLD_VELOCITY = 200;
  25.  
  26.     @Override
  27.     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  28.         try {
  29.             float diffAbs = Math.abs(e1.getY() - e2.getY());
  30.             float diff = e1.getX() - e2.getX();
  31.  
  32.             if (diffAbs > SWIPE_MAX_OFF_PATH)
  33.                 return false;
  34.  
  35.             // Left swipe
  36.             if (diff > SWIPE_MIN_DISTANCE
  37.                     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
  38.                 onLeftSwipe();
  39.             }
  40.             // Right swipe
  41.             else if (-diff > SWIPE_MIN_DISTANCE
  42.                     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
  43.                 onRightSwipe();
  44.             }
  45.         } catch (Exception e) {}
  46.         return false;
  47.     }
  48. }
Устанавливается примерно так:
  1. @Override
  2. public void onLoadFinished(Loader<List<File>> loader, List<File> data) {
  3.     mAdapter.setListItems(data);
  4.     if (isResumed()) setListShown(true);
  5.     else setListShownNoAnimation(true);
  6.  
  7.     getListView().setCacheColorHint(Color.TRANSPARENT);
  8.     getListView().setVerticalFadingEdgeEnabled(true);
  9.     getListView().setDivider(null);
  10.     getListView().setFastScrollEnabled(true);
  11.     getListView().setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
  12.     getListView().setSelector(new ColorDrawable(Color.TRANSPARENT));
  13.  
  14.      ((FileChooserActivity) getActivity()).setSwipeListener( getListView());
  15. }

Реклама

Мы в соцсетях

tw tg yt gt