手势识别官方教程(8)拦截触摸事件,得到触摸的属性如速度,距离等,控制view展开
onInterceptTouchEvent可在onTouchEvent()前拦截触摸事件,
ViewConfiguration得到触摸的属性如速度,距离等,
TouchDelegate控制view展开
Managing Touch Events in a ViewGroup
Handling touch events in a ViewGroup
takes special care, because it's common for a ViewGroup
to have children that are targets for different touch events than the ViewGroup
itself. To make sure that each view correctly receives the touch events intended for it, override the onInterceptTouchEvent()
method.
Intercept Touch Events in a ViewGroup
The onInterceptTouchEvent()
method is called whenever a touch event is detected on the surface of a ViewGroup
, including on the surface of its children. If onInterceptTouchEvent()
returns true
, the MotionEvent
is intercepted, meaning it will be not be passed on to the child, but rather to the onTouchEvent()
method of the parent.
The onInterceptTouchEvent()
method gives a parent the chance to see any touch event before its children do. If you return true
from onInterceptTouchEvent()
, the child view that was previously handling touch events receives an ACTION_CANCEL
, and the events from that point forward are sent to the parent's onTouchEvent()
method for the usual handling. onInterceptTouchEvent()
can also return false
and simply spy on events as they travel down the view hierarchy to their usual targets, which will handle the events with their own onTouchEvent()
.
如果在ViewGroup的 onInterceptTouchEvent() 返回ture ,那么表示ViewGroup拦截这个事件,它和它的子view的onTouchEvent()不会被调用。
In the following snippet, the class MyViewGroup
extends ViewGroup
. MyViewGroup
contains multiple child views. If you drag your finger across a child view horizontally, the child view should no longer get touch events, and MyViewGroup
should handle touch events by scrolling its contents. However, if you press buttons in the child view, or scroll the child view vertically, the parent shouldn't intercept those touch events, because the child is the intended target. In those cases, onInterceptTouchEvent()
should return false
, and MyViewGroup
's onTouchEvent()
won't be called.
1 public class MyViewGroup extends ViewGroup { 2 3 private int mTouchSlop; 4 5 ... 6 7 ViewConfiguration vc = ViewConfiguration.get(view.getContext()); 8 mTouchSlop = vc.getScaledTouchSlop(); 9 10 ... 11 12 @Override 13 public boolean onInterceptTouchEvent(MotionEvent ev) { 14 /* 15 * This method JUST determines whether we want to intercept the motion. 16 * If we return true, onTouchEvent will be called and we do the actual 17 * scrolling there. 18 */ 19 20 21 final int action = MotionEventCompat.getActionMasked(ev); 22 23 // Always handle the case of the touch gesture being complete. 24 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 25 // Release the scroll. 26 mIsScrolling = false; 27 return false; // Do not intercept touch event, let the child handle it 28 } 29 30 switch (action) { 31 case MotionEvent.ACTION_MOVE: { 32 if (mIsScrolling) { 33 // We're currently scrolling, so yes, intercept the 34 // touch event! 35 return true; 36 } 37 38 // If the user has dragged her finger horizontally more than 39 // the touch slop, start the scroll 40 41 // left as an exercise for the reader 42 final int xDiff = calculateDistanceX(ev); 43 44 // Touch slop should be calculated using ViewConfiguration 45 // constants. 46 if (xDiff > mTouchSlop) { 47 // Start scrolling! 48 mIsScrolling = true; 49 return true; 50 } 51 break; 52 } 53 ... 54 } 55 56 // In general, we don't want to intercept touch events. They should be 57 // handled by the child view. 58 return false; 59 } 60 61 @Override 62 public boolean onTouchEvent(MotionEvent ev) { 63 // Here we actually handle the touch event (e.g. if the action is ACTION_MOVE, 64 // scroll this container). 65 // This method will only be called if the touch event was intercepted in 66 // onInterceptTouchEvent 67 ... 68 } 69 }
Note that ViewGroup
also provides a requestDisallowInterceptTouchEvent()
method. The ViewGroup
calls this method when a child does not want the parent and its ancestors to intercept touch events with onInterceptTouchEvent()
.
Use ViewConfiguration Constants
The above snippet uses the current ViewConfiguration
to initialize a variable called mTouchSlop
. You can use the ViewConfiguration
class to access common distances, speeds, and times used by the Android system.
"Touch slop" refers to the distance in pixels a user's touch can wander before the gesture is interpreted as scrolling. Touch slop is typically used to prevent accidental scrolling when the user is performing some other touch operation, such as touching on-screen elements.
Two other commonly used ViewConfiguration
methods are getScaledMinimumFlingVelocity()
and getScaledMaximumFlingVelocity()
. These methods return the minimum and maximum velocity (respectively) to initiate a fling, as measured in pixels per second. For example:
可以用ViewConfiguration的成员函数得到常用的数据,如:
vc.getScaledTouchSlop();
vc.getScaledMinimumFlingVelocity();
vc.getScaledMaximumFlingVelocity();等等
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 ... 7 8 case MotionEvent.ACTION_MOVE: { 9 ... 10 float deltaX = motionEvent.getRawX() - mDownX; 11 if (Math.abs(deltaX) > mSlop) { 12 // A swipe occurred, do something 13 } 14 15 ... 16 17 case MotionEvent.ACTION_UP: { 18 ... 19 } if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity 20 && velocityY < velocityX) { 21 // The criteria have been satisfied, do something 22 } 23 }
Extend a Child View's Touchable Area
Android provides the TouchDelegate
class to make it possible for a parent to extend the touchable area of a child view beyond the child's bounds. This is useful when the child has to be small, but should have a larger touch region. You can also use this approach to shrink the child's touch region if need be.
In the following example, an ImageButton
is the "delegate view" (that is, the child whose touch area the parent will extend). Here is the layout file:
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 7 <ImageButton android:id="@+id/button" 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:background="@null" 11 android:src="@drawable/icon" /> 12 </RelativeLayout>
The snippet below does the following:
- Gets the parent view and posts a
Runnable
on the UI thread. This ensures that the parent lays out its children before calling thegetHitRect()
method. ThegetHitRect()
method gets the child's hit rectangle (touchable area) in the parent's coordinates. - Finds the
ImageButton
child view and callsgetHitRect()
to get the bounds of the child's touchable area. - Extends the bounds of the
ImageButton
's hit rectangle. - Instantiates a
TouchDelegate
, passing in the expanded hit rectangle and theImageButton
child view as parameters. - Sets the
TouchDelegate
on the parent view, such that touches within the touch delegate bounds are routed to the child.
ImageButton
child view, the parent view will receive all touch events. If the touch event occurred within the child's hit rectangle, the parent will pass the touch event to the child for handling. 1 public class MainActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 // Get the parent view 8 View parentView = findViewById(R.id.parent_layout); 9 10 parentView.post(new Runnable() { 11 // Post in the parent's message queue to make sure the parent 12 // lays out its children before you call getHitRect() 13 @Override 14 public void run() { 15 // The bounds for the delegate view (an ImageButton 16 // in this example) 17 Rect delegateArea = new Rect(); 18 ImageButton myButton = (ImageButton) findViewById(R.id.button); 19 myButton.setEnabled(true); 20 myButton.setOnClickListener(new View.OnClickListener() { 21 @Override 22 public void onClick(View view) { 23 Toast.makeText(MainActivity.this, 24 "Touch occurred within ImageButton touch region.", 25 Toast.LENGTH_SHORT).show(); 26 } 27 }); 28 29 // The hit rectangle for the ImageButton 30 myButton.getHitRect(delegateArea); 31 32 // Extend the touch area of the ImageButton beyond its bounds 33 // on the right and bottom. 34 delegateArea.right += 100; 35 delegateArea.bottom += 100; 36 37 // Instantiate a TouchDelegate. 38 // "delegateArea" is the bounds in local coordinates of 39 // the containing view to be mapped to the delegate view. 40 // "myButton" is the child view that should receive motion 41 // events. 42 TouchDelegate touchDelegate = new TouchDelegate(delegateArea, 43 myButton); 44 45 // Sets the TouchDelegate on the parent view, such that touches 46 // within the touch delegate bounds are routed to the child. 47 if (View.class.isInstance(myButton.getParent())) { 48 ((View) myButton.getParent()).setTouchDelegate(touchDelegate); 49 } 50 } 51 }); 52 } 53 }