android 在ViewGroup中处理触摸事件 [Managing Touch Events in a ViewGroup]

Managing Touch Events in a ViewGroup [在ViewGroup中管理触摸事件]


在ViewGroup中处理触摸事件需要特别注意,因为通常一个ViewGroup都有子View, 它们都是不同触摸事件的的对象。为了确保每一个View都能正确接收意图作用于它的触摸事件,覆写onInterceptTouchEvent()方法。

Intercept Touch Events in a ViewGroup [在一个ViewGroup中拦截触摸事件]

每当在ViewGroup表面,也包括它的子view的表面上检测到一个触摸事件时,onInterceptTouchEvent()方法就会被调用。如果onInterceptTouchEvent()返回true, MotionEvents就会被拦截,意味着它将不会被传递到其子View,而是传递到父View的onTouchEvent()方法。

onInterceptTouchEvent()方法使得父View有机会在其子View之前接收触摸事件。如果在父View的onInterceptTouchEvent()方法中返回true,在父View之前处理触摸事件的子View将会收到一个ACTION_CANCEL,从那一个时刻开始,之后的事件将会发送到父View的onTouchEvent方法来正常处理。onInterceptTouchEvent()也能返回false,容易的发现触摸事件将会顺着view层级到通常接收并通过它们拥有的 onTouchEvent()方法处理这些触摸事件的目标view。

在下面的代码片段中,MyViewGroup类继承于ViewGroup。MyViewGroup包含大量的子view。如果你在一个子view上水平拖动手指,子view将不会再获得触摸事件,MyViewGroup将会处理这些触摸事件让其内容滑动。然而,如果你点击子view中的Button,或者在垂直方向滑动子view,父view不应该拦截这些触摸事件,因为这个子view是触摸事件的目标。在这些情况下,onInterceptTouchEvent()应该返回false,MyViewGroup的onTouchEvent()方法将不会被调用。

ublic 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()方法,当一个子View不想让其父View和祖先View在onInterceptTouchEvent()中拦截触摸事件时,这个ViewGroup会调用这个方法。

Use ViewConfiguration Constants [使用ViewConfiguration常量]

上面的代码片段中使用当前的 ViewConfiguration 来初始化变量 mTouchSlop,你能够使用ViewConfiguration类来访问一些Android系统使用的常量,例如距离、速度和时间。

“Touch slop”是当用户的触摸事件被解释为滑动需要移动的最小像素距离。Touch slop典型的应用时为了防止意外的滑动,当用户执行其他的一些触摸操作,比如接触屏幕上的元素的时候。
两个被 常用的ViewConfiguration方法是getScaledMinimumFlingVelocity()和getScaledMaximumFlingVelocity()。这两个方法返回最小和最大速度来发起一个fling,测量单位是像素每秒。

举例:

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

Extend a Child View's Touchable Area [扩展子视图的可触摸区域]

Android提供了TouchDelegate类,使得父View能够扩展子View的触摸区域。当一个子View所占区域非常小,但是需要一个大的区域让用户触摸操作时,这个是非常有用的。如果需要缩小子View的触摸区域,也可以使用这种方法。

在下面的示例中,ImageButton就是"delegate view"(也就是需要父view扩展可触摸区域的子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>
下面的代码片段做了以下一些事情:
1.获取父view,并在UI线程中post一个Runnable。这确保了父view在调用getHitRect()方法之前列出了它的子视图。getHitRect()方法在父视图坐标系中获得子视图的可点击矩形框(可触摸区域)。
2.找到ImageButton子view并调用getHitRect()来获取子视图的的可触摸区域边界。
3.扩展ImageButton的矩形边界。
4.实例化一个TouchDelegate,并将扩充的可点击矩形区域和ImageButton子视图作为传递参数。
5.在父view上面设置TouchDelegate,如此 在扩展区域上的触摸动作会传递到子视图。

在触摸ImageButton的扩展可触摸区域中,父view将会接受所有的触摸事件,如果触摸事件发生在子视图的扩展矩形中,则父view将会把触摸事件传递给子view去处理。

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);
                }
            }
        });
    }
}


英文文档地址: http://developer.android.com/training/gestures/viewgroup.html#vc

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值