Search code examples
androidandroid-viewpager

Is it possible to disable scrolling on a ViewPager


I have a ViewPager which instantiates a View. I'd like to disable both the scrolling of the viewpager and the child buttons momentarily while a search result is returned to the view. I've calling viewPager.setEnabled(false) but this doesn't disable it.

Anyone got any ideas?


Solution

  • A simple solution is to create your own subclass of ViewPager that has a private boolean flag, isPagingEnabled. Then override the onTouchEvent and onInterceptTouchEvent methods. If isPagingEnabled equals true invoke the super method, otherwise return.

    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;
        }
    }
    

    Then in your Layout.XML file replace any <com.android.support.V4.ViewPager> tags with <com.yourpackage.CustomViewPager> tags.

    This code was adapted from this blog post.