在 ViewGroup
中处理触摸事件需要特别小心,因为 ViewGroup
通常会有子视图,而这些子视图会成为与 ViewGroup
本身不同的触摸事件的目标。为了确保每个视图正确接收为其设计的触摸事件,请重写 onInterceptTouchEvent()
方法。
请参阅以下相关资源
在 ViewGroup 中拦截触摸事件
onInterceptTouchEvent()
方法在检测到 ViewGroup
表面(包括其子视图表面)发生触摸事件时调用。如果 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()
方法。当子视图不希望父视图及其祖先使用 onInterceptTouchEvent()
拦截触摸事件时,ViewGroup
会调用此方法。
处理 ACTION_OUTSIDE 事件
如果 ViewGroup
收到带有 ACTION_OUTSIDE
的 MotionEvent
,默认情况下该事件不会分发给其子视图。要处理带有 ACTION_OUTSIDE
的 MotionEvent
,可以重写 dispatchTouchEvent(MotionEvent event)
以分发给相应的 View
,或者在相关的 Window.Callback
(例如 Activity
)中处理。
使用 ViewConfiguration 常量
前面的代码段使用当前的 ViewConfiguration
初始化了一个名为 mTouchSlop
的变量。您可以使用 ViewConfiguration
类访问 Android 系统使用的常见距离、速度和时间。
“触摸斜率 (Touch slop)”是指用户的触摸可以在手势被解释为滚动之前偏移的像素距离。触摸斜率通常用于防止用户在执行其他触摸操作(例如触摸屏幕元素)时意外滚动。
另外两个常用的 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); } } }); } }