【Touch&input 】管理ViewGroup中的触摸事件(9)

在a中处理触摸事件ViewGroup需要格外小心,因为一般情况下ViewGroup,让孩子成为不同于ViewGroup 本身的触摸事件的目标。为了确保每个视图都能正确接收预定给它的触摸事件,请覆盖该onInterceptTouchEvent()方法。

请参阅以下相关资源:

拦截ViewGroup中的触摸事件


onInterceptTouchEvent() 每当在ViewGroup包括其子表面上的表面上检测到触摸事件时调用该方法 。如果 onInterceptTouchEvent() 返回true,MotionEvent则被截获,这意味着它不会传递给孩子,而是传递给onTouchEvent()父级的 方法。

该onInterceptTouchEvent() 方法让父母有机会在其子女面前看到触摸事件。如果您true从中 返回onInterceptTouchEvent(),之前处理触摸事件的子视图会收到一个ACTION_CANCEL,并且从该点开始的事件将发送到父级 onTouchEvent()方法以进行常规处理。 onInterceptTouchEvent()也可以返回false并简单地监视事件,因为它们沿着视图层次传递到它们通常的目标,这些目标将自己处理事件 onTouchEvent()。

在下面的代码片段中,这个类MyViewGroup扩展了 ViewGroup。 MyViewGroup包含多个子视图。如果您将手指水平拖过子视图,则子视图不应再获取触摸事件,并且 MyViewGroup应该通过滚动其内容来处理触摸事件。但是,如果按子视图中的按钮或垂直滚动​​子视图,父级不应拦截这些触摸事件,因为子级是预定目标。在这种情况下, onInterceptTouchEvent()应该返回false,并MyViewGroup的 onTouchEvent()将不会被调用。

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 JUST determines whether we want to intercept the motion.
         * If we return true, onTouchEvent will be called and we 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; // Do not intercept touch event, let the child handle it
        }

        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                if (mIsScrolling) {
                    // We're currently scrolling, so yes, intercept the
                    // touch event!
                    return true;
                }

                // If the user has dragged her finger horizontally more than
                // the touch slop, start the scroll

                // left as an exercise for the reader
                final int xDiff = calculateDistanceX(ev);

                // Touch slop should be calculated using ViewConfiguration
                // constants.
                if (xDiff > mTouchSlop) {
                    // Start scrolling!
                    mIsScrolling = true;
                    return true;
                }
                break;
            }
            ...
        }

        // In general, we don't want to intercept touch events. They should be
        // handled by the child view.
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE,
        // scroll this container).
        // This method will only be called if the touch event was intercepted in
        // onInterceptTouchEvent
        ...
    }
}

请注意,ViewGroup也提供了一种 requestDisallowInterceptTouchEvent()方法。在ViewGroup调用此方法时,一个孩子不希望父母和祖先拦截触摸事件与 onInterceptTouchEvent()。

处理ACTION_OUTSIDE事件

如果ViewGroup收到一个MotionEvent 带有ACTION_OUTSIDE,该事件将不会默认派遣其子。要处理一个MotionEvent with ACTION_OUTSIDE,可以重写 dispatchTouchEvent(MotionEvent event) 以分派给适当的View,或者在相关的Window.Callback(例如Activity)中处理它 。

使用ViewConfiguration常量


上面的代码片段使用当前ViewConfiguration初始化一个变量调用mTouchSlop。您可以使用ViewConfiguration该类访问Android系统使用的常见距离,速度和时间。

“触摸斜率”是指在手势被解释为滚动之前,用户的触摸可以漫游的像素距离。触摸坡度通常用于防止用户在执行其他触摸操作(例如触摸屏幕元素)时发生意外滚动。

另外两种常用的ViewConfiguration方法是 getScaledMinimumFlingVelocity() 和getScaledMaximumFlingVelocity()。这些方法会返回最小和最大速度(分别)以启动一次投掷,以像素/秒为单位进行测量。例如:

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 occurred, do something
    }

...

case MotionEvent.ACTION_UP: {
    ...
    } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
            && velocityY < velocityX) {
        // The criteria have been satisfied, do something
    }
}

延伸子视图的可触摸区域


Android提供了这个TouchDelegate类,使父母可以将子视图的可触摸区域扩展到孩子的范围之外。当孩子必须很小时,这是很有用的,但是应该有一个更大的触摸区域。如果需要,您也可以使用这种方法缩小孩子的触摸区域。

在下面的示例中,an 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>

下面的代码片段执行以下操作:

  • 获取父视图并Runnable在UI线程上发布一个。这可确保父母在调用getHitRect()方法之前布置子女。该getHitRect()方法在父级坐标中获取子级的命中矩形(可触摸区域)。
  • 查找ImageButton子视图并调用getHitRect()以获取儿童可触摸区域的边界。
  • 扩展ImageButton命中矩形的边界。
  • 实例化一个TouchDelegate传入展开的命中矩形和ImageButton子视图作为参数。
  • TouchDelegate在父视图上设置,使触摸委托范围内的触摸路由到子项

作为ImageButton子视图的触摸委托,父视图将接收所有触摸事件。如果触摸事件发生在孩子的命中矩形内,父母会将触摸事件传递给孩子进行处理。

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 (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 should receive motion
                // events.
                TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
                        myButton);

                // Sets the TouchDelegate on the parent view, such that touches
                // within the touch delegate bounds are routed to the child.
                if (View.class.isInstance(myButton.getParent())) {
                    ((View) myButton.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }
}
Lastest Update:2018.04.25

联系我

QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

公众号推荐:

【Touch&input 】管理ViewGroup中的触摸事件(9)

猜你喜欢

转载自blog.51cto.com/4789781/2124888
今日推荐