管理ViewGroup中的触摸事件

编写:Andrwyw - 原文:http://developer.android.com/training/gestures/viewgroup.html

因为很多时候是用ViewGroup的子类来做不同触摸事件的目标,而不是ViewGroup本身,所以处理ViewGroup中的触摸事件需要特别注意。 为了确保每个view能正确地接收到它们想要的触摸事件,可以重写onInterceptTouchEvent()函数。

在ViewGroup中截获触摸事件

每当在ViewGroup(包括它的子View)的表面上检测到一个触摸事件,onInterceptTouchEvent()都会被调用。如果onInterceptTouchEvent()返回trueMotionEvent就被截获了,这表示它不会被传递给其子View,而是传递给该父view自身的onTouchEvent()方法。

onInterceptTouchEvent()方法让父view能够在它的子view之前处理触摸事件。如果我们让onInterceptTouchEvent()返回true,则之前处理触摸事件的子view会收到ACTION_CANCEL事件,并且该点之后的事件会被发送给该父view自身的onTouchEvent()函数,进行常规处理。onInterceptTouchEvent()也可以返回false,这样事件沿view层级分发到目标前,父view可以简单地观察该事件。这里的目标是指,通过onTouchEvent()处理消息事件的view。

接下来的代码段中,MyViewGroup继承自ViewGroupMyViewGroup有多个子view。如果我们在某个子View上水平地拖动手指,该子view不会接收到触摸事件,而是应该由MyViewGroup处理这些触摸事件来滚动它的内容。然而,如果我们点击子view中的button,或垂直地滚动子view,则父view不会截获这些触摸事件,因为子view本身就是预定目标。在这些情况下,onInterceptTouchEvent()应该返回falseMyViewGrouponTouchEvent()也不会被调用。

  1. public class MyViewGroup extends ViewGroup {
  2. private int mTouchSlop;
  3. ...
  4. ViewConfiguration vc = ViewConfiguration.get(view.getContext());
  5. mTouchSlop = vc.getScaledTouchSlop();
  6. ...
  7. @Override
  8. public boolean onInterceptTouchEvent(MotionEvent ev) {
  9. /*
  10. * This method JUST determines whether we want to intercept the motion.
  11. * If we return true, onTouchEvent will be called and we do the actual
  12. * scrolling there.
  13. */
  14. final int action = MotionEventCompat.getActionMasked(ev);
  15. // Always handle the case of the touch gesture being complete.
  16. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
  17. // Release the scroll.
  18. mIsScrolling = false;
  19. return false; // Do not intercept touch event, let the child handle it
  20. }
  21. switch (action) {
  22. case MotionEvent.ACTION_MOVE: {
  23. if (mIsScrolling) {
  24. // We're currently scrolling, so yes, intercept the
  25. // touch event!
  26. return true;
  27. }
  28. // If the user has dragged her finger horizontally more than
  29. // the touch slop, start the scroll
  30. // left as an exercise for the reader
  31. final int xDiff = calculateDistanceX(ev);
  32. // Touch slop should be calculated using ViewConfiguration
  33. // constants.
  34. if (xDiff > mTouchSlop) {
  35. // Start scrolling!
  36. mIsScrolling = true;
  37. return true;
  38. }
  39. break;
  40. }
  41. ...
  42. }
  43. // In general, we don't want to intercept touch events. They should be
  44. // handled by the child view.
  45. return false;
  46. }
  47. @Override
  48. public boolean onTouchEvent(MotionEvent ev) {
  49. // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE,
  50. // scroll this container).
  51. // This method will only be called if the touch event was intercepted in
  52. // onInterceptTouchEvent
  53. ...
  54. }
  55. }

注意ViewGroup也提供了requestDisallowInterceptTouchEvent()方法。当子view不想该父view和祖先view通过onInterceptTouchEvent()截获它的触摸事件时,可调用ViewGroup的该方法。

使用ViewConfiguration的常量

上面的代码段中使用了当前的ViewConfiguration来初始化mTouchSlop变量。我们可以使用ViewConfiguration类来获取Android系统常用的一些距离、速度、时间值。

“Touch slop”是指在被识别为移动的手势前,用户触摸可移动的那一段像素距离。Touch slop通常用来预防用户在做一些其他触摸操作时,出现意外地滑动,例如触摸屏幕上的组件。

另外两个常用的ViewConfiguration函数是getScaledMinimumFlingVelocity()getScaledMaximumFlingVelocity()。这两个函数会返回初始化一个快速滑动(fling)的最小、最大速度(分别地),以像素每秒为测量单位。如:

  1. ViewConfiguration vc = ViewConfiguration.get(view.getContext());
  2. private int mSlop = vc.getScaledTouchSlop();
  3. private int mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
  4. private int mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
  5. ...
  6. case MotionEvent.ACTION_MOVE: {
  7. ...
  8. float deltaX = motionEvent.getRawX() - mDownX;
  9. if (Math.abs(deltaX) > mSlop) {
  10. // A swipe occurred, do something
  11. }
  12. ...
  13. case MotionEvent.ACTION_UP: {
  14. ...
  15. } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
  16. && velocityY < velocityX) {
  17. // The criteria have been satisfied, do something
  18. }
  19. }

扩展子view的可触摸区域

Android提供了TouchDelegate类,让父view扩展超出子view自身边界的可触摸区域。这在当子view很小,但需要一个更大的触摸区域时非常有用。如果需要,我们也可以使用这种方式来实现对子view的触摸区域的收缩。

在下面的例子中,ImageButton对象是所谓的”delegate view”(是指触摸区域将被父view扩展的那个子view)。这是布局文件:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:id="@+id/parent_layout"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. tools:context=".MainActivity" >
  6. <ImageButton android:id="@+id/button"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:background="@null"
  10. android:src="@drawable/icon" />
  11. </RelativeLayout>

下面的代码段做了这样几件事:

  • 获得父view对象并发送一个Runnable到UI线程。这会确保父view在调用getHitRect()函数前会布局它的子view。getHitRect()函数会获得子view在父view坐标系中的点击矩形(触摸区域)。
  • 找到ImageButton子view,然后调用getHitRect()来获得它的触摸区域的边界。
  • 扩展ImageButton的点击矩形的边界。
  • 实例化一个TouchDelegate对象,并把扩展过的点击矩形和ImageButton子view作为参数传递给它。
  • 设置父view的TouchDelegate,这样在touch delegate边界内的点击就会传递到该子view上。

ImageButton子view的touch delegate范围内,父view会接收到所有的触摸事件。如果触摸事件发生在子view自身的点击矩形中,父view会把触摸事件交给子view处理。

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. // Get the parent view
  7. View parentView = findViewById(R.id.parent_layout);
  8. parentView.post(new Runnable() {
  9. // Post in the parent's message queue to make sure the parent
  10. // lays out its children before you call getHitRect()
  11. @Override
  12. public void run() {
  13. // The bounds for the delegate view (an ImageButton
  14. // in this example)
  15. Rect delegateArea = new Rect();
  16. ImageButton myButton = (ImageButton) findViewById(R.id.button);
  17. myButton.setEnabled(true);
  18. myButton.setOnClickListener(new View.OnClickListener() {
  19. @Override
  20. public void onClick(View view) {
  21. Toast.makeText(MainActivity.this,
  22. "Touch occurred within ImageButton touch region.",
  23. Toast.LENGTH_SHORT).show();
  24. }
  25. });
  26. // The hit rectangle for the ImageButton
  27. myButton.getHitRect(delegateArea);
  28. // Extend the touch area of the ImageButton beyond its bounds
  29. // on the right and bottom.
  30. delegateArea.right += 100;
  31. delegateArea.bottom += 100;
  32. // Instantiate a TouchDelegate.
  33. // "delegateArea" is the bounds in local coordinates of
  34. // the containing view to be mapped to the delegate view.
  35. // "myButton" is the child view that should receive motion
  36. // events.
  37. TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
  38. myButton);
  39. // Sets the TouchDelegate on the parent view, such that touches
  40. // within the touch delegate bounds are routed to the child.
  41. if (View.class.isInstance(myButton.getParent())) {
  42. ((View) myButton.getParent()).setTouchDelegate(touchDelegate);
  43. }
  44. }
  45. });
  46. }
  47. }