Subclassing ViewPager Breaks Animation
- by Ryan Thomas
In my Android application I have an activity which uses a view pager to display 4+ pages (Fragments). I implemented buttons on each screen that move between pages by calling:
pager.setCurrentItem(position, true);
The view pager and fragments are all working as I desired. I then began looking for a solution to disable user swiping between pages so that the transition between pages in handled by the buttons only. The solution I found was mentioned in a few stackoverflow articles as well as This Blog that suggest subclassing the view pager to intercept touch events to disable swiping. I followed those examples by subclassing the view pager class as follows:
public class ViewPager extends android.support.v4.view.ViewPager {
private boolean enabled;
public ViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setSwipingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Using the subclassed view pager and calling setSwipingEnabled(false) works as was desired. The user can no longer move between pages with swipe gestures and I can still move between pages via button clicks by calling setCurrentItem(int position, boolean smoothScroll). However using the subclass breaks the animation between pages. When I call setCurrentItem(position, true) with android.support.v4.view.ViewPager I get very clean scrolling animations between pages. When I make the same call using the subclass the screen has a very brief 'flash' and then automatically draws the new page.
I would like to know how to fix the animation while retaining the ability to disable user swiping between pages. I greatly appreciate any help with this. Let me know if you need any additional information. So far I have tested using a Samsung device running 2.3.5 and an AVD emulator targeting Android 2.3.3.