防止内视图onTouch时滑动ViewPager2

Prevent Swiping of ViewPager2 when onTouch of inner view(防止内视图onTouch时滑动ViewPager2)
本文介绍了防止内视图onTouch时滑动ViewPager2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)