问题描述
我有一个 ViewPager2,里面有一个片段,
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.
当内部视图拦截触摸事件时,如何防止 ViewPager 滑动?
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.
推荐答案
为内部视图设置 OnTouchListener.在 onTouch()
方法中,调用:
Set OnTouchListener for inner view. In onTouch()
method, call:
viewPager.requestDisallowInterceptTouchEvent(true)
ViewPager 在 onInterceptTouchEvent()
中处理其滑动动作.上面的代码阻止 ViewPager 调用 onInterceptTouchEvent()
.当您滑动时,ViewPager 在 onInterceptTouchEvent()
中返回 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.
当内部视图未被触摸时,设置回 false
.
Set back to false
when the inner view is not being touched.
根据我的经验,onInterceptTouchEvent()
可以防止 onTouchEvent()
.它不会阻止 OnTouchListener
.所以这里的关键是为内部视图设置OnTouchListener
.
From my experience, onInterceptTouchEvent()
prevents onTouchEvent()
. It does not prevent OnTouchListener
. So the key here is to set up OnTouchListener
for the inner view.
这篇关于防止内视图onTouch时滑动ViewPager2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!