o9s
is a microblog
home archives search feed blogroll


SwipeLinearLayout

I worked entirely way too hard on this. Hopefully this saves someone some time. This is an extended linear layout that handles left and right swipes.

public class SwipeLinearLayout extends LinearLayout {

  private static final int SWIPE_THRESHOLD = 100;

  private float startX;

  /* Constructors go here */

  @Override
  public boolean onInterceptTouchEvent(MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_DOWN) {
      startX = event.getX();
    } else if (action == MotionEvent.ACTION_MOVE) {
      float x = event.getX();
      float xDeltaTotal = x - startX;

      if (Math.abs(xDeltaTotal) > SWIPE_THRESHOLD) {
        startX = x;
        return true;
      }
    }

    return false;
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
      float x = event.getX();
      float xDeltaTotal = x - startX;

      if (xDeltaTotal > SWIPE_THRESHOLD) {
        handleLeftSwipe();
      } else if (xDeltaTotal < -SWIPE_THRESHOLD) {
        handleRightSwipe();
      }
    }

    return true;
  }

  private void handleLeftSwipe() {
  }

  private void handleRightSwipe() {
  }

}

I’m using it to implement navigation through gestures in one of my Android app.

It’s funny how much easier it was to implement in iOS.

// Left swipe.
UISwipeGestureRecognizer *swipeLeft =
  [[UISwipeGestureRecognizer alloc]
    initWithTarget:self
    action:@selector(handleLeftSwipe:)];
[swipeLeft setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.view addGestureRecognizer:swipeLeft];

// Right swipe.
UISwipeGestureRecognizer *swipeRight =
  [[UISwipeGestureRecognizer alloc]
    initWithTarget:self
    action:@selector(handleRightSwipe:)];
[swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:swipeRight];

It’s still very verbose (partially because of the verbose nature of Objective-C), but at least I didn’t need to do maths.

Posted on 2018-03-06   #android     #java     #ios     #objc  






← Next post    ·    Previous post →