在 ViewGroup
中处理触摸事件需要特别小心,因为 ViewGroup
通常包含作为不同触摸事件目标的子级,而不是 ViewGroup
本身。为了确保每个视图都正确接收为其准备的触摸事件,请重写 onInterceptTouchEvent()
方法。
请参阅以下相关资源
在 ViewGroup 中拦截触摸事件
每当在 ViewGroup
的表面(包括其子级的表面)上检测到触摸事件时,都会调用 onInterceptTouchEvent()
方法。如果 onInterceptTouchEvent()
返回 true
,则 MotionEvent
将被拦截,这意味着它不会传递给子级,而是传递到父级的 onTouchEvent()
方法。
onInterceptTouchEvent()
方法使父级有机会在子级之前查看触摸事件。如果您从 onInterceptTouchEvent()
返回 true
,则先前处理触摸事件的子视图将收到 ACTION_CANCEL
,并且从那时起发生的事件将发送到父级的 onTouchEvent()
方法以进行常规处理。onInterceptTouchEvent()
也可以返回 false
并监视事件如何在视图层次结构中向下传递到其通常的目标,这些目标使用其自己的 onTouchEvent()
处理事件。
在以下代码段中,MyViewGroup
类扩展了 ViewGroup
。MyViewGroup
包含多个子视图。如果您水平拖动手指穿过子视图,则子视图将不再获取触摸事件,并且 MyViewGroup
通过滚动其内容来处理触摸事件。但是,如果您点击子视图中的按钮或垂直滚动子视图,则父级不会拦截这些触摸事件,因为子级是预期的目标。在这些情况下,onInterceptTouchEvent()
返回 false
,并且不会调用 MyViewGroup
类的 onTouchEvent()
。
Kotlin
class MyViewGroup @JvmOverloads constructor( context: Context, private val mTouchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop ) : ViewGroup(context) { ... override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { // This method only determines whether you want to intercept the motion. // If this method returns true, onTouchEvent is called and you can do // the actual scrolling there. return when (ev.actionMasked) { // Always handle the case of the touch gesture being complete. MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> { // Release the scroll. mIsScrolling = false false // Don't intercept the touch event. Let the child handle it. } MotionEvent.ACTION_MOVE -> { if (mIsScrolling) { // You're currently scrolling, so intercept the touch event. true } else { // If the user drags their finger horizontally more than the // touch slop, start the scroll. // Left as an exercise for the reader. val xDiff: Int = calculateDistanceX(ev) // Touch slop is calculated using ViewConfiguration constants. if (xDiff > mTouchSlop) { // Start scrolling! mIsScrolling = true true } else { false } } } ... else -> { // In general, don't intercept touch events. The child view // handles them. false } } } override fun onTouchEvent(event: MotionEvent): Boolean { // Here, you actually handle the touch event. For example, if the action // is ACTION_MOVE, scroll this container. This method is only called if // the touch event is intercepted in onInterceptTouchEvent. ... } }
Java
public class MyViewGroup extends ViewGroup { private int mTouchSlop; ... ViewConfiguration vc = ViewConfiguration.get(view.getContext()); mTouchSlop = vc.getScaledTouchSlop(); ... @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // This method only determines whether you want to intercept the motion. // If this method returns true, onTouchEvent is called and you can do // the actual scrolling there. final int action = MotionEventCompat.getActionMasked(ev); // Always handle the case of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the scroll. mIsScrolling = false; return false; // Don't intercept touch event. Let the child handle it. } switch (action) { case MotionEvent.ACTION_MOVE: { if (mIsScrolling) { // You're currently scrolling, so intercept the touch event. return true; } // If the user drags their finger horizontally more than the // touch slop, start the scroll. // Left as an exercise for the reader. final int xDiff = calculateDistanceX(ev); // Touch slop is calculated using ViewConfiguration constants. if (xDiff > mTouchSlop) { // Start scrolling. mIsScrolling = true; return true; } break; } ... } // In general, don't intercept touch events. The child view handles them. return false; } @Override public boolean onTouchEvent(MotionEvent ev) { // Here, you actually handle the touch event. For example, if the // action is ACTION_MOVE, scroll this container. This method is only // called if the touch event is intercepted in onInterceptTouchEvent. ... } }
请注意,ViewGroup
还提供了一个 requestDisallowInterceptTouchEvent()
方法。ViewGroup
在子级不希望父级及其祖先使用 onInterceptTouchEvent()
拦截触摸事件时调用此方法。
处理 ACTION_OUTSIDE 事件
如果 ViewGroup
收到一个带有 ACTION_OUTSIDE
的 MotionEvent
,则默认情况下不会将其分派给其子级。要处理带有 ACTION_OUTSIDE
的 MotionEvent
,请重写 dispatchTouchEvent(MotionEvent event)
以分派到相应的 View
或在相关的 Window.Callback
中处理它,例如 Activity
。
使用 ViewConfiguration 常量
前面的代码段使用当前 ViewConfiguration
初始化一个名为 mTouchSlop
的变量。您可以使用 ViewConfiguration
类访问 Android 系统使用的常见距离、速度和时间。
“触摸容差”是指用户触摸在被解释为滚动之前可以游荡的像素距离。触摸容差通常用于防止用户执行其他触摸操作(例如触摸屏幕元素)时意外滚动。
另外两个常用的 ViewConfiguration
方法是 getScaledMinimumFlingVelocity()
和 getScaledMaximumFlingVelocity()
。这些方法分别返回以像素/秒为单位测量的启动抛掷的最小和最大速度。例如
Kotlin
private val vc: ViewConfiguration = ViewConfiguration.get(context) private val mSlop: Int = vc.scaledTouchSlop private val mMinFlingVelocity: Int = vc.scaledMinimumFlingVelocity private val mMaxFlingVelocity: Int = vc.scaledMaximumFlingVelocity ... MotionEvent.ACTION_MOVE -> { ... val deltaX: Float = motionEvent.rawX - mDownX if (Math.abs(deltaX) > mSlop) { // A swipe occurs, do something. } return false } ... MotionEvent.ACTION_UP -> { ... if (velocityX in mMinFlingVelocity..mMaxFlingVelocity && velocityY < velocityX) { // The criteria are satisfied, do something. } }
Java
ViewConfiguration vc = ViewConfiguration.get(view.getContext()); private int mSlop = vc.getScaledTouchSlop(); private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity(); private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); ... case MotionEvent.ACTION_MOVE: { ... float deltaX = motionEvent.getRawX() - mDownX; if (Math.abs(deltaX) > mSlop) { // A swipe occurs, do something. } ... case MotionEvent.ACTION_UP: { ... } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) { // The criteria are satisfied, do something. } }
扩展子视图的可触摸区域
Android 提供了 TouchDelegate
类,使父级能够将子视图的可触摸区域扩展到子视图边界之外。当子视图必须很小但需要更大的触摸区域时,这很有用。您还可以使用此方法缩小子视图的触摸区域。
在以下示例中,ImageButton
是_委托视图_,即父级扩展其触摸区域的子级。以下是布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/parent_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/icon" /> </RelativeLayout>
以下代码段完成了这些任务
- 获取父视图并在 UI 线程上发布
Runnable
。这确保了父级在调用getHitRect()
方法之前布局其子级。getHitRect()
方法获取子级在父级坐标中的_命中矩形_(或可触摸区域)。 - 查找
ImageButton
子视图并调用getHitRect()
以获取子级可触摸区域的边界。 - 扩展
ImageButton
子视图的命中矩形的边界。 - 实例化一个
TouchDelegate
,并将扩展的命中矩形和ImageButton
子视图作为参数传递。 - 在父视图上设置
TouchDelegate
,以便触摸委托边界内的触摸被路由到子级。
作为 ImageButton
子视图的触摸委托,父视图接收所有触摸事件。如果触摸事件发生在子级的命中矩形内,则父级将触摸事件传递给子级进行处理。
Kotlin
public class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Post in the parent's message queue to make sure the parent lays out // its children before you call getHitRect(). findViewById<View>(R.id.parent_layout).post { // The bounds for the delegate view, which is an ImageButton in this // example. val delegateArea = Rect() val myButton = findViewById<ImageButton>(R.id.button).apply { isEnabled = true setOnClickListener { Toast.makeText( this@MainActivity, "Touch occurred within ImageButton touch region.", Toast.LENGTH_SHORT ).show() } // The hit rectangle for the ImageButton. getHitRect(delegateArea) } // Extend the touch area of the ImageButton beyond its bounds on the // right and bottom. delegateArea.right += 100 delegateArea.bottom += 100 // Set the TouchDelegate on the parent view so that touches within // the touch delegate bounds are routed to the child. (myButton.parent as? View)?.apply { // Instantiate a TouchDelegate. "delegateArea" is the bounds in // local coordinates of the containing view to be mapped to the // delegate view. "myButton" is the child view that receives // motion events. touchDelegate = TouchDelegate(delegateArea, myButton) } } } }
Java
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the parent view. View parentView = findViewById(R.id.parent_layout); parentView.post(new Runnable() { // Post in the parent's message queue to make sure the parent lays // out its children before you call getHitRect(). @Override public void run() { // The bounds for the delegate view, which is an ImageButton in // this example. Rect delegateArea = new Rect(); ImageButton myButton = (ImageButton) findViewById(R.id.button); myButton.setEnabled(true); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Touch occurred within ImageButton touch region.", Toast.LENGTH_SHORT).show(); } }); // The hit rectangle for the ImageButton. myButton.getHitRect(delegateArea); // Extend the touch area of the ImageButton beyond its bounds on // the right and bottom. delegateArea.right += 100; delegateArea.bottom += 100; // Instantiate a TouchDelegate. "delegateArea" is the bounds in // local coordinates of the containing view to be mapped to the // delegate view. "myButton" is the child view that receives // motion events. TouchDelegate touchDelegate = new TouchDelegate(delegateArea, myButton); // Set the TouchDelegate on the parent view so that touches // within the touch delegate bounds are routed to the child. if (View.class.isInstance(myButton.getParent())) { ((View) myButton.getParent()).setTouchDelegate(touchDelegate); } } }); } }