ViewPager禁止滚动

June 10, 2018
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Override to catch pointerIndex out of range exception
// when ViewPager used with a multi-touch PhotoView to display images.
class StrongViewPager : ViewPager {

    // If ViewPagers can be scrolled.
    private var isScrollable = true

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(ev: MotionEvent): Boolean {
        return try {
            if (isScrollable) super.onTouchEvent(ev) else false
        } catch (ignore: IllegalArgumentException) {
            false
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        return try {
            if (isScrollable) super.onInterceptTouchEvent(ev) else false
        } catch (e: IllegalArgumentException) {
            false
        }
    }

    // Set ViewPager if is scrollable. Default is true, means it is scrollable.
    fun setScrollable(scrollable: Boolean) {
        isScrollable = scrollable
    }

    // Get ViewPager if is scrollable.
    fun isScrollable() = isScrollable
}