0

I'm trying to create an app where users can swipe through a deck of photos. After swiping left or right, the previous photo should be deleted and the next photo is shown.

Android's ViewPager seems ideal for this except it models a slideshow rather than a deck. How can I make it go to the same next page when the user swipes either left or right?

One way to possibly do this is by creating a set of pages that are symmetrical in either direction. Then if the ViewPager is always fixed on the middle of these pages, then it will appear to be moving in one direction. This seems more like a hack, so I was hoping someone may know a better way to do this.

  • There is also a not-very-often-used [`StackView`](http://developer.android.com/reference/android/widget/StackView.html) widget in the Android SDK, which you may find of interest as a base for a custom implementation. Alternatively, its parent, [`AdapterViewFlipper`](http://developer.android.com/reference/android/widget/AdapterViewFlipper.html), is also worth checking out. – MH. Apr 19 '15 at 18:38
  • Hmm seems like StackView does not handle user swipes though. This is why I'm looking into ViewPager, since it already handles swipes. – user2660845 Apr 19 '15 at 18:44
  • Yeah, you would have to implement the touch handling yourself, which is why I was saying *"as a base for"*. There's [another library](https://github.com/thuytrinh/android-collage-views) yet that just came to mind, but again, it's not an exact match for your requirements. I guess your own proposal would actually be a fairly viable approach too, and not too hard to realise. – MH. Apr 19 '15 at 20:06

1 Answers1

-1

You will have to make your own ViewPager that extends the original ViewPager and override the onTouchEvent method

public class CustomViewPager extends ViewPager {

    float lastX = 0;

    boolean lockScroll = false;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomViewPager(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            lastX = ev.getX();
            lockScroll = false;
            return super.onTouchEvent(ev);
        case MotionEvent.ACTION_MOVE:

            if (lastX > ev.getX()) {
                lockScroll = false;
            } else {
                lockScroll = true;
            }

            lastX = ev.getX();
            break;
        }

        lastX = ev.getX();

        if(lockScroll) {
            return false;
        } else {
            return super.onTouchEvent(ev);
        }

    }
}
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59