I have a viewpager with webviews that can potentially scroll left and right. The user can have unsaved data, in which case i want to disable the viewpager, and if the user attempts to scroll off the page, i want to show an unsaved dialog window.
I looked at this solution but it's not quite what i need. Since always returning true will disable my fragment's webview from scrolling also.
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled = true;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
}
Currently, i have a custom webview, where i override onTouch, and check if i can scroll horizontally. I have a method which checks if my webview can scroll left or right. Which seems to work correctly.
public boolean canScrollHorizontally(int direction){
final int offset = computeHorizontalScrollOffset();
final int range = computeHorizontalScrollRange() -computeHorizontalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
And an ontouch listener on my webview, which i believe is working correctly? If I return true if the user attempts to drag left and the view has space to drag. If not, i return false, which hopefully will pass the event back to the viewpager.
public boolean onTouchEvent(MotionEvent event) {
float x;
float y;
x = event.getX();
y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartDragX = x;
mStartDragY = y;
break;
case MotionEvent.ACTION_MOVE:
if(Math.abs(mStartDragX - ev.getX()) > SWIPE_MIN_DISTANCE){
if (mStartDragX < x && canScrollHorizontally(-1)) {
// Left to Right
return true;
} else if(mStartDragX > x && canScrollHorizontally(1)){
// Right to Left
return true;
}else{
// pass to viewpager?
return false;
}
}
}
return super.onTouchEvent(event);
}
My ontouch event for my viewpager is where i get a little lost, If the Pager is disabled. I want to display a dialog to the user.
@Override
public boolean onTouchEvent(MotionEvent ev) {
float x;
float y;
if(this.enabled) {
return super.onTouchEvent(ev);
} else{
x = ev.getX();
y = ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartDragX = x;
mStartDragY = y;
break;
case MotionEvent.ACTION_MOVE:
if(Math.abs(mStartDragX - ev.getX()) > SWIPE_MIN_DISTANCE){
showDialog()??
}
}
}
return true;
}
Can someone suggest the best way to do this?