Prevent Swiping of ViewPager2 when onTouch of inner view

荒凉一梦 提交于 2020-04-30 11:44:06

问题


I have a ViewPager2 with a fragment inside,

in the fragment, I have a custom view with certain touch logic that involves moving the finger.

how do I prevent the ViewPager from swiping while the inner view intercepts the touch event?

override fun onTouchEvent(event: MotionEvent?): Boolean {
    if (event?.action == MotionEvent.ACTION_DOWN || event?.action == MotionEvent.ACTION_MOVE) {
       //Do some stuff here
    }
    return true
}

while swiping this view the view pager still swipes to other pages.


回答1:


Set OnTouchListener for inner view. In onTouch() method, call:

viewPager.requestDisallowInterceptTouchEvent(true)

ViewPager handles its swiping motion in onInterceptTouchEvent(). Above code prevents ViewPager from calling onInterceptTouchEvent(). When you're swiping, ViewPager returns true in onInterceptTouchEvent() which also prevents touch events to be passed to child views. Therefore disallowing intercept allows child views to handle touch events.

Set back to false when the inner view is not being touched.

From my experience, onInterceptTouchEvent() prevents onTouchEvent(). It does not prevent OnTouchListener. So the key here is to set up OnTouchListener for the inner view.



来源:https://stackoverflow.com/questions/60328756/prevent-swiping-of-viewpager2-when-ontouch-of-inner-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!