Sunday, August 10, 2014

Android: Implementing a One-Way Lockable View Pager

While implementing a fun Android app, I came across a scenario where the ViewPager should only be swiped right-to-left. Visiting back should be restricted. Also at some points, I needed to lock the whole view pager so that it cannot be swiped at any direction.

The following code shows how I did it by extending the ViewPager class. Note that I was using the support library.


 
 import android.content.Context;
 import android.support.v4.view.ViewPager;
 import android.util.AttributeSet;
 import android.view.MotionEvent;

 public class OneWayLockableViewPager extends ViewPager {  
   private boolean enabled;  
   private float lastX;  

   public OneWayLockableViewPager(Context context, AttributeSet attrs) {  
     super(context, attrs);  
     this.enabled = true;  
   }  

   @Override  
   public boolean onTouchEvent(MotionEvent event) {  
     if (this.enabled) {  
       boolean lockScroll;  
       switch (event.getAction()) {  
         case MotionEvent.ACTION_MOVE:  
           lockScroll = lastX <= event.getX();  
           break;  
         default:  
           lockScroll = false;  
           lastX = event.getX();  
           break;  
       } 
       return lockScroll ? false : super.onTouchEvent(event);    
     }  
     return false;  
   }  

   @Override  
   public boolean onInterceptTouchEvent(MotionEvent event) {  
     if (this.enabled) {  
       return super.onInterceptTouchEvent(event);  
     }  
     return false;  
   }  

   public void lock() {  
     this.enabled = false;  
   }  

   public void unlock() {  
     this.enabled = true;  
   }  
 }  

It is quite easy to change it if you want to reverse the allowed direction of swiping. Just change the less than or equal sign to a greater than sign in line number 21.

Also when you want to lock down the whole view pager, just call the lock() method and swiping will be disabled.

No comments:

Post a Comment