Search code examples
androidandroid-viewpagerkotlin

Disable View Pager swipe of Viewpager in Kotlin


I am new to Kotlin, I have View Pager in fragment and i have set pager adapter on it. everything is working fine but when i try to stop my view pager paging swipe in Kotlin and can't find any method to do so in Kotlin. I tried to find solution on stack but no luck. Although there are many in java but not for Kotlin.

I have done this using Java as

viewPager.setPagingEnabled(false);

but whenever i try this in Kotlin i end up with error. Any help will be Appreciated.


Solution

  • UPDATE

    As of 2020 we now have ViewPager2. If you migrate to ViewPager2 there is a built in method to disable swiping: myViewPager2.isUserInputEnabled = false


    If you're not using ViewPager2 then continue with the old answer:

    I created a Kotlin version based on converting this answer from Java: https://stackoverflow.com/a/13437997/8023278

    There is no built in way to disable swiping between pages of a ViewPager, what's required is an extension of ViewPager that overrides onTouchEvent and onInterceptTouchEvent to prevent the swiping action. To make it more generalised we can add a method setSwipePagingEnabled to enable/disable swiping between pages.

    class SwipeLockableViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
        private var swipeEnabled = false
    
        override fun onTouchEvent(event: MotionEvent): Boolean {
            return when (swipeEnabled) {
                true -> super.onTouchEvent(event)
                false -> false
            }
        }
    
        override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
            return when (swipeEnabled) {
                true -> super.onInterceptTouchEvent(event)
                false -> false
            }
        }
    
        fun setSwipePagingEnabled(swipeEnabled: Boolean) {
            this.swipeEnabled = swipeEnabled
        }
    }
    

    Then in our layout xml we use our new SwipeLockableViewPager instead of the standard ViewPager

    <mypackage.SwipeLockableViewPager 
            android:id="@+id/myViewPager" 
            android:layout_height="match_parent" 
            android:layout_width="match_parent" />
    

    Now in our activity/fragment we can call myViewPager.setSwipePagingEnabled(false) and users won't be able to swipe between pages