在 ViewGroup 中管理触摸事件

ViewGroup会特别照料 因为在 ViewGroup 中,子项是不同位置的子项很常见 与 ViewGroup 本身相比。为了确保每个视图都能正确接收 触摸事件,可替换 onInterceptTouchEvent() 方法。

在 ViewGroup 中拦截轻触事件

每当在以下事件中检测到触摸事件时,系统都会调用 onInterceptTouchEvent() 方法: ViewGroup 的表面,包括其子级的表面。如果 onInterceptTouchEvent() 会返回 true,即 MotionEvent 会拦截,这意味着不会将其传递给子元素,而是传递给 onTouchEvent() 方法。

onInterceptTouchEvent() 方法让父级有机会查看触摸事件 先于其子项执行此操作。如果您从onInterceptTouchEvent()退回 true, 之前处理触摸事件的子视图会收到 ACTION_CANCEL, 并且从该时间点开始的事件会发送到父级的 onTouchEvent() 方法 进行常规处理onInterceptTouchEvent() 还可以返回 false 和 在事件沿视图层次结构向下移动至其常用目标时监视事件,这些目标负责处理 事件使用自己的 onTouchEvent()

在以下代码段中,MyViewGroup 类扩展了 ViewGroupMyViewGroup 包含多个子视图。如果您用手指在子视图上拖动 在水平方向上,子视图不再获取轻触事件,而 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 收到 MotionEventACTION_OUTSIDE, 默认情况下,系统不会将该事件分派给其子项。要使用以下代码处理 MotionEventACTION_OUTSIDE,任一替换项 dispatchTouchEvent(MotionEvent event) 分派给相应的 View 或 在相关的 Window.Callback - 用于 示例 Activity

使用 ViewConfiguration 常量

上述代码段使用当前的 ViewConfiguration 来初始化变量 名为 mTouchSlop。您可以使用 ViewConfiguration 类来访问 Android 系统常用的距离、速度和时间。

“Touch slop”是指在做出相应手势之前,用户触摸可移动的距离(以像素为单位) 解释为滚动。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 是 _delegate view_ — 即父项扩展其触摸区域的子项。其布局文件如下:

<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>

以下代码段完成了这些任务:

  • 获取父视图并发布 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);
                }
            }
        });
    }
}