Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

android - Prevent Swiping of ViewPager2 when onTouch of inner view

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...