Простой Swipe-листенер для View (Fragment или Activity)
- private GestureDetector gestureDetector;
- View.OnTouchListener gestureListener;
- public void setSwipeListener(View v) {
- if (v == null) return;
- gestureDetector = new GestureDetector(this, new SwipeGestureDetector());
- gestureListener = new View.OnTouchListener() {
- public boolean onTouch(View v, MotionEvent event) {
- return gestureDetector.onTouchEvent(event);
- }
- };
- v.setOnTouchListener(gestureListener);
- }
- private void onLeftSwipe() { }
- private void onRightSwipe() {
- onBackPressed();
- }
- private class SwipeGestureDetector extends SimpleOnGestureListener {
- private static final int SWIPE_MIN_DISTANCE = 50;
- private static final int SWIPE_MAX_OFF_PATH = 200;
- private static final int SWIPE_THRESHOLD_VELOCITY = 200;
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
- try {
- float diffAbs = Math.abs(e1.getY() - e2.getY());
- float diff = e1.getX() - e2.getX();
- if (diffAbs > SWIPE_MAX_OFF_PATH)
- return false;
- // Left swipe
- if (diff > SWIPE_MIN_DISTANCE
- && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
- onLeftSwipe();
- }
- // Right swipe
- else if (-diff > SWIPE_MIN_DISTANCE
- && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
- onRightSwipe();
- }
- } catch (Exception e) {}
- return false;
- }
- }
Устанавливается примерно так:
- @Override
- public void onLoadFinished(Loader<List<File>> loader, List<File> data) {
- mAdapter.setListItems(data);
- if (isResumed()) setListShown(true);
- else setListShownNoAnimation(true);
- getListView().setCacheColorHint(Color.TRANSPARENT);
- getListView().setVerticalFadingEdgeEnabled(true);
- getListView().setDivider(null);
- getListView().setFastScrollEnabled(true);
- getListView().setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
- getListView().setSelector(new ColorDrawable(Color.TRANSPARENT));
- ((FileChooserActivity) getActivity()).setSwipeListener( getListView());
- }