In my Android application, I am using a viewpager for image swiping. My requirement is, if a user swipes out of the first and last page, the activity should finish.
I have taken this example. But the method setOnSwipeOutListener
is not called in my activity.
This is my custom view pager class:
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
float mStartDragX;
OnSwipeOutListener mListener;
public void setOnSwipeOutListener(OnSwipeOutListener listener) {
mListener = listener;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
float x = ev.getX();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartDragX = x;
break;
case MotionEvent.ACTION_MOVE:
if (mStartDragX < x && getCurrentItem() == 0) {
mListener.onSwipeOutAtStart();
} else if (mStartDragX > x
&& getCurrentItem() == getAdapter().getCount() - 1) {
mListener.onSwipeOutAtEnd();
}
break;
}
return super.onInterceptTouchEvent(ev);
}
public interface OnSwipeOutListener {
public void onSwipeOutAtStart();
public void onSwipeOutAtEnd();
}
}
And below in my activity class I call setOnSwipeOutListener
method on my custom viewpager class, but it does not get called.
myPager = (CustomViewPager) findViewById(R.id.home_pannels_pager);
.......
myPager.setOnSwipeOutListener(new OnSwipeOutListener() { // the method never called
@Override
public void onSwipeOutAtStart() {
Log.e("swipe Out At Start ", "swipe out");
}
@Override
public void onSwipeOutAtEnd() {
Log.e("swipe Out At End ", "swipe end");
}
});
myPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int po) {
Log.e("positon", ""+po);
}
});
Please help me to detect if the user has swiped beyond the first and last page to close this activity and how to call the method from code.