Search code examples
androidxamarinxamarin.androidandroid-viewpager

Is there a way to disable the swiping between Tabbed Page on Android in Xamarin Native android?


I'm new to xamarin and I'm trying to disable swipe by creating a custom Viewpager but I cant find touch listener interface in Viewpager. Is there any way to do this?

public class CustomViewPager : ViewPager   
 {
        Context _context;

        public CustomViewPager(Context context) : base(context)
        {
            _context = context;
        }

        public CustomViewPager(Context context, IAttributeSet arg1) : base(context, arg1)
        {
            _context = context;
        }

        public bool IsPagerDisabled { get; set; }

        /*public override Boolean OnTouchEvent(MotionEvent event)
        {
            if (!IsPagerDisabled)
            {
                return base.OnTouchEvent(event);
            }
            else
            {
                return false;
            }
        }*/
    }

Solution

  • I recently did a similar implementation and this seems to work like a charm:

    using Android.Content;
    using Android.Support.V4.View;
    using Android.Views;
    
    public class LockableViewPager : ViewPager
    {
        public bool SwipeLocked { get; set; }
    
        Context mContext;
    
        public LockableViewPager(Context context) : base(context)
        {
            Init(context, null);
        }
        public LockableViewPager(Context context, Android.Util.IAttributeSet attrs) : base(context, attrs)
        {
            Init(context, attrs);
        }
        private void Init(Context ctx, Android.Util.IAttributeSet attrs)
        {
            mContext = ctx;
        }
    
        public override bool OnTouchEvent(MotionEvent ev)
        {
            return !SwipeLocked && base.OnTouchEvent(ev);
        }
    
        public override bool OnInterceptTouchEvent(MotionEvent e)
        {
            return !SwipeLocked && base.OnInterceptTouchEvent(e);
        }
    
        public override bool CanScrollHorizontally(int direction)
        {
            return !SwipeLocked && base.CanScrollHorizontally(direction);
        }
    
    }
    

    How to use it?

    In xml:

    <_yourNameSpace.LockableViewPager 
      auto:SwipeLocked="true"
    

    where auto is

    xmlns:auto="http://schemas.android.com/apk/res-auto"
    

    In code :

    LockableViewPager viewpager= new LoackableViewpager();
    Viewpager.SwipeLocked=true;