Skip to content

Instantly share code, notes, and snippets.

@xuhaibahmad
Created July 30, 2018 07:38
Show Gist options
  • Save xuhaibahmad/0c4e2855a7a91dcba4a859ac19a14dc3 to your computer and use it in GitHub Desktop.
Save xuhaibahmad/0c4e2855a7a91dcba4a859ac19a14dc3 to your computer and use it in GitHub Desktop.
A View pager that can only be swiped programmatically
import android.annotation.SuppressLint
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.DecelerateInterpolator
import android.widget.Scroller
/**
* Created by Zuhaib Ahmad on 30/7/2018.
* <p>
* A View pager that can only be swiped programmatically.
*/
class NonSwipeableViewPager : ViewPager {
constructor(context: Context) : super(context) {
addSmoothScroller()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
addSmoothScroller()
}
// Never allow swiping to switch between pages
override fun onInterceptTouchEvent(event: MotionEvent): Boolean = false
// Never allow swiping to switch between pages
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean = false
// Added for smooth scrolling
private fun addSmoothScroller() = try {
ViewPager::class.java.getDeclaredField("mScroller").apply {
isAccessible = true
set(this, SmoothScroller(context))
}
} catch (e: Exception) {
e.printStackTrace()
}
inner class SmoothScroller(context: Context) : Scroller(context, DecelerateInterpolator()) {
override fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int, duration: Int) =
super.startScroll(startX, startY, dx, dy, 350)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment